<template>
  <a-modal
    :title="title"
    :width="width"
    :bodyStyle="bodyStyle"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :footer="null"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

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

        <template v-if="model.isCpOn===1 || model.isCpOn==='1'">
        <a-form-item label="服务费率" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number :min="0.01" :max="99.99" v-decorator="[ 'cpServiceRate', {rules: [{ required: true, message: '请输入服务费率' }],initialValue:model.cpServiceRate}]"
                          :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" :precision="2"
                          placeholder="请输入服务费率"
                          style="width: 100%"/>
        </a-form-item>

          <a-form-item label="打款银行" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
            <a-checkbox-group :options="plainOptions"  v-model="valueInfo" @change="onChange" />
          </a-form-item>

          <a-form-item label="合同" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-upload
              name="file"
              :multiple="true"
              :remove="handleDelete"
              :action="uploadAction"
              :headers="headers"
              :data="{'isup':1,'bizPath':bizPath}"
              :fileList="fileList"
              :beforeUpload="beforeUpload"
              @change="handleChange">
              <a-button> <a-icon type="upload" /> 选择上传 </a-button>
            </a-upload>
          </a-form-item>
        </template>






      </a-form>
    </a-spin>
    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-button class="ant-btn"  @click="handleCancel">取消</a-button>
      <a-button class="ant-btn ant-btn-primary" style="margin-left: 8px"  @click="handleOk">确定</a-button>
    </div>
  </a-modal>
</template>

<script>

  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { httpAction,getAction, deleteAction, putAction, postAction,downFile } from '@/api/manage'
  import JUpload from '@/components/jeecg/JUpload'
  import pick from 'lodash.pick'


  const FILE_TYPE_ALL = "all"
  const FILE_TYPE_PDF = 'pdf'
  const uidGenerator = () => {
    return '-' + parseInt(Math.random() * 10000 + 1, 10)
  }
  const getFileName = (path) => {
    if (path.lastIndexOf('\\') >= 0) {
      let reg = new RegExp('\\\\', 'g')
      path = path.replace(reg, '/')
    }
    return path.substring(path.lastIndexOf('/') + 1)
  }

  export default {
    name: "HlgCompanyPayModal ",
    components: {

    },
    data () {
      return {
        bankInfoList:[],
        plainOptions:[],
        valueInfo:[],
        headers: {},
        fileList: [],
        form: this.$form.createForm(this),
        title:"操作",
        width:800,
        bodyStyle: {
          paddingTop: '20px',
          paddingBottom:'50px',
          height: (window.innerHeight * 0.42) + 'px',
          'overflow-y': 'auto'
        },
        disableSubmit:false,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        companyId: 0,
        validatorRules:{
          cpServiceRate:{rules: [{ required: true, message: '请输入服务费率!' }]},
          isCpOn:{rules: [{ required: true, message: '请选择是否开启' }]},
        },
        url: {
          edit: "/hlgcompany/hlgCompany/editCompanyPay",
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
          imgerver: window._CONFIG['imgDomainOssURL'],
          queryBankInfo: "/hlgcpmanager/hlgCpSetting/cpSetting",
        }
     
      }
    },
    props: {
      fileType: {
        type: String,
        required: false,
        default: FILE_TYPE_ALL
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath: {
        type: String,
        required: false,
        default: '/hlgjob/hlgSubContract'
      },
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }
    },
    computed: {
      uploadAction: function() {
        return this.url.fileUpload
      }
    },
    methods: {
      add (record) {
        this.edit(record);
      },
      edit (record) {
        this.form.resetFields();
        this.model={}
        this.model = Object.assign({}, record);
        this.companyId = this.model.id;
        this.plainOptions=[],
        this.valueInfo=[]
        this.bankInfoList=[]
        if(this.model.id){
          this.queryBankInfo();
        }
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'isCpOn','cpServiceRate','cpBankInfo','cpServiceContract'))
          this.form.setFieldsValue({ isCpOn:this.model.isCpOn!=null? String(this.model.isCpOn):''})
          this.editFileList(this.model.cpServiceContract)
        })
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        if(!this.model.cpBankInfo){
          this.$message.error('请选择打款银行');
          return
        }
        const that = this;
        const { fileList } = that
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            httpurl+=this.url.edit;
            method = 'put';
            var cpServiceContract = "";
            let formData = Object.assign(this.model, values);
            let isDone = true;
            fileList.forEach((file,index) => {
              if(!file.thUrl){
                isDone = false;
              }
              if(index === 0){
                cpServiceContract = file.thUrl;
              }else{
                cpServiceContract += "," + file.thUrl;
              }
            });
            //上传文件出错
            if(!isDone){
              that.$message.error("正在上传，请稍后提交!");
              that.confirmLoading = false
              return;
            }
            formData.cpServiceContract = cpServiceContract;
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
         
        })
      },
      handleCancel () {
        this.close()
      },
      changeIsOn(val){
        this.model.isCpOn = val
      },
      //查询打款信息配置的所有银行信息数据
      queryBankInfo(){
        var that=this
        getAction(that.url.queryBankInfo,{}).then((res)=>{
          if(res.success){
              if(res.result.bankInfo.length>0){
                this.bankInfoList=JSON.parse(res.result.bankInfo)
                for (let i = 0; i <this.bankInfoList.length ; i++) {
                  var arr={label: this.bankInfoList[i].bankName+this.bankInfoList[i].bankAccount.substring(this.bankInfoList[i].bankAccount.length-4), value: i}
                  that.plainOptions.push(arr)
                }
                if(that.model.cpBankInfo){
                  var cpBankInfoList=JSON.parse(that.model.cpBankInfo)
                  for (let i = 0; i <cpBankInfoList.length ; i++) {
                    for (let j = 0; j < this.bankInfoList.length ; j++) {
                      if(this.bankInfoList[j].bankAccount===cpBankInfoList[i].bankAccount){
                        that.valueInfo.push(j)
                      }
                    }
                  }
                }
              }
          }
        });
      },
      onChange(checkedValues){
        if(checkedValues.length>0){
          var cpBankInfo1=[]
          for (let i = 0; i <checkedValues.length ; i++) {
            cpBankInfo1.push(this.bankInfoList[checkedValues[i]])
            this.model.cpBankInfo=JSON.stringify(cpBankInfo1)
          }
        }else{
          this.model.cpBankInfo=null
        }
      },

      handlePathChange() {
        let uploadFiles = this.fileList
        let path = ''
        if (!uploadFiles || uploadFiles.length == 0) {
          path = ''
        }
        let arr = []

        for (var a = 0; a < uploadFiles.length; a++) {
          arr.push(uploadFiles[a].response.message)
        }
        if (arr.length > 0) {
          path = arr.join(',')
        }
        this.$emit('change', path)
        console.log(1111,this.fileList)
      },



      beforeUpload: function(file) {
        //TODO 验证文件大小
      },

      handleChange(info) {
        let fileList = info.fileList
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            fileList = fileList.map((file) => {
              if (file.response) {
                file.url = this.url.imgerver + file.response.message
                file.thUrl = file.response.message
              }
              return file
            })
          }
          this.$message.success(`${info.file.name} 上传成功!`)
        }else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`)
        } else if (info.file.status === 'removed') {
          this.handleDelete(info.file)
        }
        this.fileList = fileList
      },

      //移除文件
      handleDelete(file){
        const index = this.fileList.indexOf(file);
        const newFileList = this.fileList.slice();
        newFileList.splice(index, 1);
        this.fileList = newFileList;
      },


      //回显文件所用
      editFileList(paths) {
        if (!paths || paths.length == 0) {
          //return [];
          // update-begin- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
          this.fileList = []
          return
          // update-end- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
        }
        let fileList = []
        let arr = paths.split(',')
        for (var a = 0; a < arr.length; a++) {
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(arr[a]),
            status: 'done',
            url: this.url.imgerver +  arr[a],
            thUrl: arr[a]
          })
        }
        this.fileList = fileList
      },

    }
  }
</script>
<style>
  .drawer-bootom-button {
    position: absolute;
    bottom: -8px;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }
  .avatar-uploader > .ant-upload {
    width: 104px;
    height: 104px;
  }

  .ant-upload-select-picture-card i {
    font-size: 49px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>