<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.bussinessuserinfo_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="success"
                   size="small"
                   @click="handleBatchImport">批量导入
        </el-button>
      </template>
      <template slot="registerStatus" slot-scope="{row}">
        <el-tag plain type="warning" size="small" v-if="row.registerStatus === 100">资料完善中</el-tag>
        <el-tag plain type="primary" size="small" v-if="row.registerStatus === 98">送审中</el-tag>
        <el-tag plain type="warning" size="small" v-if="row.registerStatus === 102">审核中</el-tag>
        <el-tag plain type="success" size="small" v-if="row.registerStatus === 200">审核成功</el-tag>
        <el-tag plain type="danger" size="small" v-if="row.registerStatus === 400">审核失败</el-tag>
        <el-tag plain type="danger" size="small" v-if="row.registerStatus === 99">送审失败</el-tag>
      </template>
      <!-- 操作菜单 -->
        <template slot-scope="{row}" slot="menu">
          <div>
              <el-button v-if="row.registerStatus === 100 || row.registerStatus === 99 || row.registerStatus === 400" style="color:orange;"type="text" size="small" plain class="none-border" @click.stop="submitRegister(row.id)">提交申请</el-button>
              <el-button v-if="row.registerStatus === 200 && permission.bussinessuserinfo_withdraw" style="color:green;" type="text" size="small" plain class="none-border" @click.stop="showPay(row.id)">发起代付</el-button>
              <el-button v-if="row.registerStatus === 200 && permission.bussinessuserinfo_withdrawrecords" style="color:red;"type="text" size="small" plain class="none-border" @click.stop="handleWithdrawRecordsView(row.id)">账单记录</el-button>
          </div>
        </template>
    </avue-crud>
    <el-dialog title="用户进件申请记录" :append-to-body="true" :visible.sync="registerRequestVisible" top="1vh" @close="closeRequestDialog" :close-on-click-modal="false">
      <bussiness-register-request :user-info-id="userInfoId" v-if="registerRequestVisible"></bussiness-register-request>
    </el-dialog>
    <el-dialog title="用户账单记录" :append-to-body="true" :visible.sync="withdrawRecordsVisible" top="1vh" @close="closeWithdrawRecordsDialog" :close-on-click-modal="false" width="80%">
      <bussiness-user-withdraw :user-info-id="userInfoId" v-if="withdrawRecordsVisible"></bussiness-user-withdraw>
    </el-dialog>
    <el-dialog title="发起用户收款" :append-to-body="true" :visible.sync="withdrawVisible" top="5vh" @close="closeWithdrawDialog" :close-on-click-modal="false" width="50%">
      <el-form ref="payForm" :model="payForm" :rules="payRules" label-width="120px">
        <el-form-item label="收款账户名：" prop="userName">
          <span>{{payForm.userName}}</span>
        </el-form-item>
        <el-form-item label="收款账户：" prop="bankCardNo">
          <span>{{payForm.bankCardNo}}</span>
        </el-form-item>
        <el-form-item label="开户行编码：" prop="bankCode">
          <span>{{payForm.bankCode}}</span>
        </el-form-item>
        <el-form-item label="预留手机号：" prop="userPhone">
          <span>{{payForm.userPhone}}</span>
        </el-form-item>
        <el-form-item label="收款金额（元）：" prop="orderAmount" label-width="140px">
          <el-input v-model="payForm.orderAmount"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="withdrawOrder(payForm)">提交</el-button>
          <el-button @click="resetWithdrawOrderForm('payForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="用户数据导入"
               append-to-body
               :visible.sync="excelBox"
               width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/bussinessmng/bussinessuserinfo";
  import {payToUser} from "@/api/bussinessmng/bussinessuserwithdraw";
  import {mapGetters} from "vuex";
  import {userRegister} from "@/api/bussinessmng/bussinessregisterrequest";
  import bussinessRegisterRequest from "../bussinessmng/bussinessregisterrequest.vue"
  import bussinessUserWithdraw from "../bussinessmng/bussinessuserwithdraw.vue"

  export default {
    components: {
      bussinessRegisterRequest, bussinessUserWithdraw
    },
    data() {
      return {
        excelBox: false,
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '模板上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              loadText: '模板上传中，请稍等',
              span: 24,
              propsHttp: {
                res: 'data'
              },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: "/api/bussiness/pay/import-payToUser-excel"
            },
          ]
        },
        excelForm: {},
        userInfoId: null,
        registerRequestVisible: false,
        withdrawVisible: false,
        withdrawRecordsVisible: false,
        isLoading: false,
        selectionList: [],
        option: {
          height:'auto',
          menuWidth: 300,
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          delBtn: false,
          selection: true,
          dialogClickModal: false,
          group:[
            {
              label: '收款人信息',
              collapse:true,
              prop: "merchantSubjectInfo",
              column: [ {
                label: "姓名",
                prop: "userName",
                hide: true,
                rules: [{
                  required: true,
                  message: "请输入收款人姓名",
                  trigger: "blur"
                }]
              },
                {
                  label: "手机号",
                  prop: "userPhone",
                  search: true,
                  rules: [{
                    required: true,
                    message: "请输入手机号",
                    trigger: "blur"
                  }]
                },]
            },
            {
              label: '账户信息',
              collapse:true,
              prop: "accountInfo",
              column: [
                {
                  label: "账户类型",
                  prop: "bankAccountType",
                  type: "select",
                  labelWidth: 110,
                  span:8,
                  hide: true,
                  value:"DEBIT_CARD",
                  dicData:[
                    {
                      label:"借记卡",
                      value:"DEBIT_CARD"
                    },
                    {
                      label:"存折",
                      value:"PASSBOOK"
                    }
                  ],
                  rules: [{
                    required: true,
                    message: "请输入银行账户类型",
                    trigger: "blur"
                  }]
                },
                {
                  label: "开户行",
                  prop: "bankCode",
                  span:8,
                  labelWidth: 110,
                    type: "select",
                    dicUrl: "/api/cyzh-guosen/bankcode/listBankCode?name={{key}}",
                    props:{
                      label: "name",
                        value: "code"
                    },
                  hide: true,
                    remote:true,
                    filterable: true,
                    placeholder:"输入关键字可搜索",
                  rules: [{
                    required: true,
                    message: "请输入开户总行编码",
                    trigger: "blur"
                  }]
                },
                {
                  label: "银行账户号码",
                  prop: "bankCardNo",
                  span:8,
                  labelWidth: 110,
                  hide: true,
                  rules: [{
                    required: true,
                    message: "请输入银行账户号码",
                    trigger: "blur"
                  }]
                },
              ]
            },
            {
              label: '证件信息',
              collapse: true,
              prop: "merchantCorporationInfo",
              column: [
                {
                  label: "身份证号",
                  prop: "userLicenceNo",
                  span: 12,
                  labelWidth: 100,
                  hide: true,
                  rules: [{
                    required: true,
                    message: "请输入用户证件号",
                    trigger: "blur"
                  }]
                },
                {
                  label: "身份证类型",
                  prop: "userLicenceType",
                  type: "select",
                  span: 12,
                  labelWidth: 110,
                  dicData:[
                    {
                      label:"身份证",
                      value:"ID_CARD"
                    },
                    {
                      label:"护照",
                      value: "PASSPORT"
                    },
                    {
                      label:"港澳居民往来内地通行证",
                      value: "HM_VISITORPASS"
                    },
                    {
                      label:"台胞证",
                      value: "TAIWAN"
                    },
                    {
                      label:"士兵证",
                      value: "SOLDIER"
                    },
                    {
                      label:"军官证",
                      value: "OFFICERS"
                    },
                  ],
                  rules: [{
                    required: true,
                    message: "请选择用户证件类型",
                    trigger: "blur"
                  }]
                },
                {
                  label: "身份证件正面照",
                  prop: "userCardFrontUrl",
                  type: "upload",
                  span: 12,
                  hide:true,
                  labelWidth: 130,
                  listType: "picture-img",
                  action: '/api/putObject',
                  propsHttp: {
                    url: 'data'
                  },
                  rules: [{
                    required: true,
                    message: "请上传身份证件正面照",
                    trigger: "blur"
                  }]
                },
                {
                  label: "身份证件反面照",
                  prop: "userCardBackUrl",
                  type: "upload",
                  span: 12,
                  hide:true,
                  labelWidth: 130,
                  listType: "picture-img",
                  action: '/api/putObject',
                  propsHttp: {
                    url: 'data'
                  },
                  rules: [{
                    required: true,
                    message: "请输入身份证件反面照",
                    trigger: "blur"
                  }]
                },
              ],
            },
          ],
          column: [
            {
              label: "收款人姓名",
              prop: "userName",
              search: true,
              searchLabelWidth: 100,
              display: false,
            },
            {
              label: "所属采购商",
              prop: "bussinessId",
              labelWidth: 100,
              search: true,
              searchLabelWidth: 100,
              addDisplay: false,
              editDisplay: false,
              type: "select",
              filterable: true,
              dicUrl: "/api/cyzh-guosen/bussiness/listBussiness?size=500",
              props:{
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择所属采购商",
                trigger: "blur"
              }]
            },
            {
              label: "进件状态",
              prop: "registerStatus",
              type: "select",
              search: true,
              slot: true,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=merchant_register_status",
              display: false,
              props:{
                label: "dictValue",
                value: "dictKey"
              },
            },
            {
              label: "审核意见",
              prop: "auditOpinion",
              disabled: true,
              addDisplay: false,
              editDisplay: false,
              rules: [{
                required: false,
                message: "请输入审核意见",
                trigger: "blur"
              }]
            },
            {
              label: "创建时间",
              prop: "createTime",
              type: "date",
              addDisplay: false,
              editDisplay: false,
              valueFormat: "yyyy-MM-dd HH:mm:ss"
            },
            {
              label: "更新时间",
              prop: "updateTime",
              type: "date",
              addDisplay: false,
              editDisplay: false,
              valueFormat: "yyyy-MM-dd HH:mm:ss"
            },
          ]
        },
        data: [],
        payForm:{userInfoId: '', orderAmount: '', userName:'', bankCode: '', userPhone: ''},
        payRules: {
          orderAmount: [
            { required: true, message: '收款金额必填', trigger: 'blur' },
            { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请正确填写收款金额,可保留两位小数' },
          ],
        }
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.bussinessuserinfo_add, false),
          viewBtn: this.vaildData(this.permission.bussinessuserinfo_view, false),
          delBtn: this.vaildData(this.permission.bussinessuserinfo_delete, false),
          editBtn: this.vaildData(this.permission.bussinessuserinfo_edit, false),
          withdrawBtn: this.vaildData(this.permission.bussinessuserinfo_withdraw, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleBatchImport(){
        this.excelBox = true;
      },
      uploadAfter(res, done, loading, column) {
        window.console.log(column);
        this.excelBox = false;
        this.refreshChange();
        done();
      },
      resetWithdrawOrderForm(formName){
        this.payForm.orderAmount = '';
      },
      showPay(rowId){
        let that = this;
        getDetail(rowId).then(res => {
          that.payForm.userInfoId = res.data.data.id;
          that.payForm.userName = res.data.data.userName;
          that.payForm.bankCardNo = res.data.data.bankCardNo;
          that.payForm.bankCode = res.data.data.bankCode;
          that.payForm.userPhone = res.data.data.userPhone;
          that.withdrawVisible = true;
        });
      },
      closeRequestDialog(){
        this.registerRequestVisible = false;
      },
      closeWithdrawDialog(){
        this.withdrawVisible = false;
      },
      closeWithdrawRecordsDialog(){
        this.withdrawRecordsVisible = false;
      },
      handleRegisterRequestView(userInfoId){
        this.userInfoId = userInfoId;
        this.registerRequestVisible = true;
      },
      handleWithdrawRecordsView(userInfoId){
        this.userInfoId = userInfoId;
        this.withdrawRecordsVisible = true;
      },
      submitRegister(userInfoId) {
        this.$confirm("确定提交进件申请吗?如果需要修改，请先修改后再提交申请", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          userRegister({"userInfoId": userInfoId}).then(() => {
            this.$message({
              type: "success",
              message: "提交成功，请等待审核结果"
            });
            this.onLoad(this.page);
          });
        });
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      withdrawOrder(payForm){
        payToUser(payForm).then(res =>{
          this.$message({
            type: "success",
            message: res.data.msg
          });
          this.withdrawVisible = false;
        })
      }
    }
  };
</script>

<style>
</style>
