<template>
  <page-layout>
  <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item label="平台支付" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag type="list" v-decorator="['isOn',validatorRules.isOn]" :trigger-change="true" @change="changeIsOn"
                             dictCode="is_cp_on" placeholder="请选择平台支付" style="width: 100%"/>
        </a-form-item>

        <template v-if="model.isOn==='1'|| model.isOn===1 ">
        <a-form-item label="付款企业" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
          <template v-if="!model.id">
            <a-input-search
              placeholder="选择企业"
              disabled
              v-decorator="[ 'companyName', {rules: [{ required: true, message: '请选择企业' }],initialValue:model.companyName}]"
              @search="onSearch1">
              <a-button slot="enterButton" icon="search">选择</a-button>
            </a-input-search>
          </template>
          <template v-else>
            <a-input v-decorator="[ 'companyName',  {rules: [{ required: true, message: '请选择企业' }],initialValue:model.companyName}]"  :disabled="true"></a-input>
          </template>
        </a-form-item>

        <a-form-item label="服务商" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
            <a-input-search
              placeholder="选择服务商"
              disabled
              v-decorator="[ 'subcontractorName',  {rules: [{ required: true, message: '请选择服务商' }],initialValue:model.subcontractorName}]"
              @search="onSearch">
              <a-button slot="enterButton" icon="search" >选择</a-button>
            </a-input-search>
        </a-form-item>

        <a-form-item label="打款信息" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
        <div v-for="(item,index) in hlgBankInfoList" :key="index">
          <a-row :gutter="24" style="margin-top: 20px">
            <a-col :lg="19" :md="18" :sm="18">
              <div class="ant-alert ant-alert-info" style="padding: 8px 14px 8px 14px;">
                <a-form-item label="银行卡号" :colon="true" :labelCol="labelCol1" :wrapperCol="wrapperCol1" style="margin-bottom: 10px">
                  <span style="margin-left: 10px">{{item.bankAccount}}</span>
                </a-form-item>
                <a-form-item label="开户银行" :labelCol="labelCol1" :wrapperCol="wrapperCol1" style="margin-bottom: 10px">
                  <span style="margin-left: 10px">{{item.bankName}}</span>
                </a-form-item>
                <a-form-item label="开户地" :labelCol="labelCol1" :wrapperCol="wrapperCol1" style="margin-bottom: 10px">
                  <span style="margin-left: 10px">{{item.bankAddress}}</span>
                </a-form-item>
              </div>
            </a-col>
            <template v-if="!model.id">
            <a-col :lg="5" :md="6" :sm="6">
              <div style="display: flex;flex-direction: column;">
                <a-button @click="editRowCustom(index)" class="ant-btn ant-btn-primary" style="padding: 0 12px;">编辑</a-button>
                <a-button @click="delRowCustom(index)" class="ant-btn ant-btn-danger" style="margin-top: 10px;padding: 0 12px;">删除</a-button>
              </div>
            </a-col>
            </template>
          </a-row>
        </div>
        </a-form-item>

        <a-form-item label=" " :colon="false" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-button icon="plus" @click="addRowCustom" shape="round">添加</a-button>
        </a-form-item>
        </template>

        <a-form-item
          :wrapperCol="{ span: 24 }"
          style="text-align: center"
        >
          <a-button class="ant-btn ant-btn-primary"  @click="handleOk">提交</a-button>
        </a-form-item>

      </a-form>
    </a-spin>
    <select-company-pay-window ref="companyWindow" @ok="modalFormOk1"></select-company-pay-window>
    <select-company-subcontractor-window ref="selectSubcontractWindow" @ok="modalFormOk3"></select-company-subcontractor-window>
    <company-pay-bank-information-modal  ref="companyBankInfoWindow" @ok="modalFormOk2"></company-pay-bank-information-modal>
  </a-card>
  </page-layout>
</template>

<script>

  import { httpAction,getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import JDate from '@/components/jeecg/JDate'
  import PageLayout from '@/components/page/PageLayout'
  import SelectCompanyPayWindow from './SelectCompanyPayWindow'
  import SelectCompanySubcontractorWindow from '../../hlgpayment/modules/SelectCompanySubcontractorWindow'
  import CompanyPayBankInformationModal from './CompanyPayBankInformationModal'

  
  export default {
    name: "HlgCpSettingModal",
    components: {
      CompanyPayBankInformationModal,
      SelectCompanySubcontractorWindow,
      SelectCompanyPayWindow,
      JDate,
      PageLayout
    },
    data () {
      return {
        hlgBankInfoList:[],
        selectedDepartKeys1:[], //保存用户选择企业id
        checkedDepartKeys1:[],
        selectedDepartKeys:[], //保存用户选择服务商id
        checkedDepartKeys:[],
        companyId:0,
        selectSubcontractorId:0,
        form: this.$form.createForm(this),
        title:"操作",
        width:800,
        visible: false,
        model: {},
        labelCol: {
          lg: {span: 7}, sm: {span: 7}
        },
        wrapperCol: {
          lg: {span: 10}, sm: {span: 17}
        },
        labelCol1: {
          lg: {span: 5}, sm: {span: 5}
        },
        wrapperCol1: {
          lg: {span: 10}, sm: {span: 17}
        },
        confirmLoading: false,
        validatorRules:{
        companyId:{rules: [{ required: true, message: '请选择企业' }]},
        subcontractorId:{rules: [{ required: true, message: '请选择服务商' }]},
        bankInfo:{rules: [{ required: true, message: '请输入银行信息!' }]},
        isOn:{rules: [{ required: true, message: '请选择是否开启' }]},
        createTime:{rules: [{ required: true, message: '请输入创建时间!' }]},
        createBy:{rules: [{ required: true, message: '请输入创建者!' }]},
        updateTime:{},
        updateBy:{},
        },
        url: {
          add: "/hlgcpmanager/hlgCpSetting/add",
          edit: "/hlgcpmanager/hlgCpSetting/edit",
          cpSetting: "/hlgcpmanager/hlgCpSetting/cpSetting",
        }
     
      }
    },
    created () {
      this.edit({})
    },
    methods: {
      add () {
        this.edit({});
      },
      edit () {
        this.hlgBankInfoList=[]
        this.selectSubcontractorId=0
        this.companyId=0
        this.confirmLoading = true;
        getAction(this.url.cpSetting, {}).then((res) => {
          if (res.success) {
            this.model=Object.assign({}, res.result);
            if(this.model.bankInfo){
              this.hlgBankInfoList=JSON.parse(this.model.bankInfo)
              this.selectSubcontractorId=this.model.subcontractorId
              this.companyId=this.model.companyId
            }
            this.confirmLoading = false;
            this.visible = true;
            this.$nextTick(() => {
              this.form.setFieldsValue(pick(this.model,'companyId','subcontractorId','bankInfo','isOn','createTime','createBy','updateTime','updateBy','companyName','subcontractorName'))
              this.form.setFieldsValue({ isOn:this.model.isOn!=null? String(this.model.isOn):''})
            })
          }
        })
      },



      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            if(this.hlgBankInfoList.length===0){
              this.$message.warning('请添加打款信息')
              return
            }
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            formData.subcontractorId = this.selectSubcontractorId;
            formData.companyId = this.companyId;
            formData.bankInfo = JSON.stringify(this.hlgBankInfoList);
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                this.model.id=res.result.id
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
         
        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'companyId','subcontractorId','bankInfo','isOn','createTime','createBy','updateTime','updateBy'))
      },
      changeIsOn(val){
        this.model.isOn = val
      },
      //搜索企业
      onSearch1(){
        this.$refs.companyWindow.add(this.checkedDepartKeys1);
      },
      // 获取用户选择企业提交的返回数据
      modalFormOk1 (formData) {
        this.selectedDepartKeys1 = [];
        for (let i = 0; i < formData.departIdList.length; i++) {
          this.selectedDepartKeys1.push(formData.departIdList[i].key);
          this.form.setFieldsValue({ companyName: formData.departIdList[i].title })
        }
        this.checkedDepartKeys1 = this.selectedDepartKeys1  //更新当前的选择keys
        if(this.selectedDepartKeys1[0]){
          this.companyId = this.selectedDepartKeys1[0];
        }
        //若有服务商信息，则清空
        this.selectSubcontractorId = 0;
        this.form.setFieldsValue({ subcontractorName: null })
      },


      //搜索服务商
      onSearch(){
        this.$refs.selectSubcontractWindow.add(this.checkedDepartKeys,this.companyId);
      },

      // 获取用户选择服务商弹提交的返回数据
      modalFormOk3 (formData) {
        this.selectedDepartKeys = [];
        for (let i = 0; i < formData.departIdList.length; i++) {
          this.selectedDepartKeys.push(formData.departIdList[i].key);
          this.form.setFieldsValue({ subcontractorName: formData.departIdList[i].title })

        }
        this.checkedDepartKeys = this.selectedDepartKeys  //更新当前的选择keys
        if(this.selectedDepartKeys[0]){
          this.selectSubcontractorId = this.selectedDepartKeys[0];
        }
      },

      editRowCustom (index) {
        this.$refs.companyBankInfoWindow.edit(this.hlgBankInfoList[index],2,index) //1:新增 2：编辑
        this.$refs.companyBankInfoWindow.title = '打款信息'
        this.$refs.companyBankInfoWindow.disableSubmit = false
      },
      delRowCustom (index) {
        this.hlgBankInfoList.splice(index,1);
        this.$forceUpdate();
      },
      addRowCustom () {
        var record ={}
        this.$refs.companyBankInfoWindow.edit(record,1,0)   //1:新增 2：编辑  (新增默认index为0)
        this.$refs.companyBankInfoWindow.title = '打款信息'
        this.$refs.companyBankInfoWindow.disableSubmit = false
      },
      modalFormOk2(data,addtype,index){
        for (let i = 0; i <this.hlgBankInfoList.length ; i++) {
          if(this.hlgBankInfoList[i].bankAccount===data.bankAccount){
            this.$message.warning('银行卡号重复，请重新添加');
            return
          }
        }
        if(addtype===1){
          this.hlgBankInfoList.push(data);
        }else{
          this.hlgBankInfoList[index]=data;

        }
        this.$forceUpdate();
      }


    }
  }
</script>
