<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
    :footer="null"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" style="padding-bottom: 30px;padding-top: 30px">

<!--        <a-form-item label="下载模板" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--          <a-button :ghost='true' type='primary'><a-icon type="download"/>下载模板</a-button>-->
<!--        </a-form-item>-->

        <a-form-item label="上传文件" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload name="file" :showUploadList="showUploadList" :fileList="fileList" :multiple="false" :headers="headers" :action="importExcelUrl()" @change="handleImportExcel2">
            <a-button><a-icon type="upload"/>导入付款</a-button>
          </a-upload>
        </a-form-item>

        <template v-if="type==2">
          <a-form-item label="上传成功" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <p>上传成功</p>
          </a-form-item>
        </template>

        <a-form-item label="服务商" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="false">
          <span>{{model.subcontractorName}}</span>
        </a-form-item>


        <a-form-item label="服务费率" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <span>{{model.serviceRate}}%</span>
        </a-form-item>


        <a-form-item label="账户余额" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <span style="color: #2eabff">{{model.balance}}</span>
        </a-form-item>

        <template v-if="type==1">
          <a-form-item label="上传失败" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a @click="delrequire(dataError)">查看错误项</a>
          </a-form-item>
        </template>




      </a-form>
    </a-spin>
    <hw-payment-export-error-modal ref="modalSelectRequireForm"></hw-payment-export-error-modal>
    <company-select-window ref="companyWindow" @ok="modalFormOk1"></company-select-window>
   <select-company-subcontractor-window ref="selectSubcontractWindow" @ok="modalFormOk"></select-company-subcontractor-window>
    <div class="drawer-bootom-button">
      <a-button class="ant-btn ant-btn-primary"  @click="handleCancel">关闭</a-button>
    </div>
  </a-modal>

</template>

<script>
  import { httpAction } from '@/api/manage'
  import JDate from '@/components/jeecg/JDate'
  import JUpload from '@/components/jeecg/JUpload'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { getAction, deleteAction, putAction, postAction,downFile } from '@/api/manage'
  import HwPaymentExportErrorModal from './HwPaymentExportErrorModal'
  import CompanySelectWindow from '../../requiremanager/modules/CompanySelectWindow'
  import SelectCompanySubcontractorWindow from './SelectCompanySubcontractorWindow'
  const tyemplateGeneration = (params) => putAction('/hwpayment/hwPaymentDetail/tyemplateGeneration', params)

  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: 'HwPaymentExportModal',
    components: {
      SelectCompanySubcontractorWindow,
      CompanySelectWindow,
      HwPaymentExportErrorModal,
      JDate,
      JUpload,
      JSelectDepart,
      JDictSelectTag
    },
    data() {
      return {
        selectSubcontractorId:0,
        selectedDepartKeys1:[], //保存用户选择企业id
        checkedDepartKeys1:[],
        selectedDepartKeys:[], //保存用户选择服务商id
        checkedDepartKeys:[],
        companyId:null,
        dataError:"",
        uploadAction: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
        urlDownload: window._CONFIG['domianURL'] + '/hpSys/common/ossDownload',
        headers: {},
        fileList: [],
        type:0,
        showUploadList:false,
        form: this.$form.createForm(this),
        title: '操作',
        width: 600,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        defaultFileList:[],
        accept:'.pdf',
        confirmLoading: false,
        validatorRules: {
          companyId:{ rules: [{ required: true, message: '请输入所属平台企业!' }] },
        },
        url: {
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
          edit: '/hwuser/hwUser/edit',
          importExcelUrl: "/hwpayment/hwPaymentDetail/importExcel",
          exportXlsUrl:"/hwpayment/hwPaymentDetail/tyemplateGeneration",
          queryBalance:"/saasmanager/hwPlatformCompanyAccount/queryBalance"
        }

      }
    },

    watch: {

    },
    created() {
      this.type=0
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }

    },
    methods: {
      add() {
        this.edit({})
      },
      edit(record) {
        this.form = this.$form.createForm(this)
        this.type=0
        this.model={}
        this.fileList=[]
        this.form.resetFields()
        console.log(666666,record)
        this.visible = true
        this.showUploadList = false;
        this.selectedDepartKeys1 = [];
        this.checkedDepartKeys1 = [];
        this.selectedDepartKeys = [];
        this.checkedDepartKeys = [];
        this.selectSubcontractorId=0
        this.companyId=null

      },
      close() {
        this.$emit('ok')
        this.visible = false
      },
      handleOk() {
        this.$emit('ok')
        this.visible = false
      },
      handleCancel() {
        this.$emit('ok')
        this.close()
      },
      popupCallback(row) {

      },

      importExcelUrl(){
        var companyId = null;
        this.form.validateFields((err, values) => {
          if (!err) {
            if (this.selectedDepartKeys1[0]) {
              companyId = this.companyId
            }
          }
        })
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },

      /* 导入 */
      handleImportExcel2(info){

        this.showUploadList = true;
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        let fileList = info.fileList
        //第二导入删除前一个文件
        if(fileList.length>1){
          const index = 0;
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          fileList=newFileList
        }
        if (info.file.status === 'done') {
          if(info.file.response.success){
            this.type=2
            this.$message.success(`${info.file.name} 文件上传成功`);
            var datas=JSON.parse(info.file.response.message)[0]
            this.model.subcontractorName=datas.subcontractorName
            this.model.balance=datas.balance
            this.model.serviceRate=datas.serviceRate
            this.model.serviceRate=datas.serviceRate
          } else {
            if(info.file.response.message=="您导入的付款单需在同一需求"){
              this.$message.error(info.file.response.message);
              return
            }
            if(info.file.response.message=="单次付款明细不能超过999条"){
              this.$message.error(info.file.response.message);
              return
            }
            if(info.file.response.message=="需求服务商与选择服务商不符"){
              this.$message.error(info.file.response.message);
              return
            }
            if(info.file.response.message=="文件导入失败:请先配置支付类型"){
              this.$message.error(info.file.response.message);
              return
            }
            if(info.file.response.message=="订单所属企业与当前登录人企业不符"){
              this.$message.error(info.file.response.message);
              return
            }
            this.type=1
            this.dataError=info.file.response.message
            console.log(this.dataError)
            this.$message.error(`导入失败`);
          }
        } else if (info.file.status === 'error') {
          this.$message.error(`文件上传失败: ${info.file.msg} `);
        }
        this.fileList = fileList
      },

      delrequire(dataError){
        this.$refs.modalSelectRequireForm.edit(dataError)
        this.$refs.modalSelectRequireForm.title = '错误项'
        this.$refs.modalSelectRequireForm.disableSubmit = false
      },
      handleExportXls(fileName){
        if(!fileName || typeof fileName != "string"){
          fileName = "导出文件"
        }
        let param = {...this.queryParam};
        if(this.selectedRowKeys && this.selectedRowKeys.length>0){
          param['selections'] = this.selectedRowKeys.join(",")
        }
        console.log("导出参数",param)
        downFile(this.url.exportXlsUrl,param).then((data)=>{
          console.log("导出参数",param)

          if (!data) {
            this.$message.warning("文件下载失败")
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data]), fileName+'.xls')
          }else{
            let url = window.URL.createObjectURL(new Blob([data]))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName+'.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          }
        })
      },


      //搜索企业
      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 })
          // this.form.setFieldsValue({ balance: null })
          this.model.balance=null
        }
      },


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

      // 获取用户选择服务商弹提交的返回数据
      modalFormOk (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.form.setFieldsValue({ balance: formData.departIdList[i].balance })
          this.model.balance=formData.departIdList[i].balance
          this.model.cpType=formData.departIdList[i].cpType
          this.form.setFieldsValue({ serviceRate: formData.departIdList[i].serviceRate })
          this.model.serviceRate=formData.departIdList[i].serviceRate;
        }
        this.checkedDepartKeys = this.selectedDepartKeys  //更新当前的选择keys
        if(this.selectedDepartKeys[0]){
          this.selectSubcontractorId = this.selectedDepartKeys[0];
        }
      },


    }
  }
</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;
  }
</style>