<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" :required="true">
          <template v-if="!model.id">
            <a-input-search
              placeholder="选择企业"
              disabled
              v-decorator="[ 'companyName', validatorRules.companyId]"
              @search="onSearch1">
              <a-button slot="enterButton" icon="search" v-if="!model.id">选择</a-button>
            </a-input-search>
          </template>
          <template v-else>
            <a-input v-decorator="[ 'companyName', validatorRules.companyId]"  :disabled="true"></a-input>
          </template>
        </a-form-item>


        <a-form-item label="服务商" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
          <template v-if="!model.id">
            <a-input-search
              placeholder="选择服务商"
              disabled
              v-decorator="[ 'subcontractorName', validatorRules.subcontractorId]"
              @search="onSearch">
              <a-button slot="enterButton" icon="search" v-if="!model.id">选择</a-button>
            </a-input-search>
          </template>
          <template v-else>
            <a-input v-decorator="[ 'subcontractorName', validatorRules.subcontractorId]"  :disabled="true"></a-input>
          </template>
        </a-form-item>


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


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

        <template>
          <a-form-item label="下载模板" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-button
              :ghost="true"
              type="primary"
              icon="download"
              size="small"
              @click="handleExportXls('付款模板')">
              下载
            </a-button>
          </a-form-item>
        </template>


        <a-form-item label="上传文件" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
          <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>


        <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>
    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-button class="ant-btn ant-btn-primary" style="margin-left: 8px"  @click="handleOk">关闭</a-button>
    </div>
    <hw-payment-export-error-modal ref="modalSelectRequireForm"  @ok="modalFormOk"></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>
  </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 './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: 'HlgPaymentImportModal',
    components: {
      SelectCompanySubcontractorWindow,
      CompanySelectWindow,
      HwPaymentExportErrorModal,
      JDate,
      JUpload,
      JSelectDepart,
      JDictSelectTag
    },
    data() {
      return {
        disableSubmit:false,
        selectedDepartKeys1:[], //保存用户选择企业id
        checkedDepartKeys1:[],
        selectedDepartKeys:[], //保存用户选择服务商id
        checkedDepartKeys:[],
        companyId:0,
        selectSubcontractorId:0,
        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: 800,
        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: '请选择付款企业!' }]},
          subcontractorId:{ rules: [{ required: true, message: '请选择服务商!' }]},
        },
        url: {
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
          importExcelUrl: "/hlgpayment/hlgPayment/importExcel?companyId=",
          exportXlsUrl:"/hlgpayment/hlgPaymentDetail/tyemplateGeneration"
        }

      }
    },

    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.type=0
        this.model={}
        this.fileList=[]
        this.form.resetFields()
        this.model = record
        console.log(666666,record)
        this.visible = true
        this.showUploadList = false;
        this.selectedDepartKeys = [];
        this.checkedDepartKeys = [];
        this.selectedDepartKeys1 = [];
        this.checkedDepartKeys1 = [];
        this.companyId=0
        this.selectSubcontractorId=0
      },
      close() {
        this.$emit('ok')
        this.visible = false
        this.selectedDepartKeys = [];
        this.checkedDepartKeys = [];
        this.selectedDepartKeys1 = [];
        this.checkedDepartKeys1 = [];
        this.companyId=0
        this.selectSubcontractorId=0
      },
      handleOk() {
            this.$emit('ok')
            this.visible = false
      },
      handleCancel() {
        this.close()
      },
      popupCallback(row) {

      },

      importExcelUrl(){
        if(this.companyId===0){
          return
        }
        if(this.selectSubcontractorId===0){
          return
        }
        this.model.serviceRate=this.form.getFieldValue("serviceRate")
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`+this.companyId+"&subcontractorId="+this.selectSubcontractorId+"&cpType="+this.model.cpType+"&serviceRate="+this.model.serviceRate;
      },

      /* 导入 */
      handleImportExcel2(info){
        if(this.companyId===0){
          this.$message.error('请先选择付款企业');
          return
        }
        if(this.selectSubcontractorId===0){
          this.$message.error('请先选择服务商');
          return
        }
        this.model.serviceRate=this.form.getFieldValue("serviceRate")
        if(!this.model.serviceRate){
          this.$message.error('请先填写服务费率');
          return
        }
        this.fileList=[]
        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') {
          this.type=2
          if(info.file.response.success){
            this.$message.success(`${info.file.name} 文件上传成功`);
          } else {
            this.dataError=info.file.response.message
            if(JSON.parse(this.dataError)[0].reason=="单次付款明细不能超过999条"){
              this.$message.error(info.file.response.message);
              return
            }
            if(JSON.parse(this.dataError)[0].reason=="60天内已存在相同笔数相同金额的付款"){
              this.$success({
                title: '提示',
                content: '您的公司支付过相同人数相同金额的付款单，请确认是否为重复导入，如果误操作，请在列表中删除此条付款。',
                okText: '确定',
                centered:true,
                onOk: () => {

                }
              })
              this.fileList = fileList
              return
            }
            this.type=1
            this.$message.error(`导入失败`);
            return
          }
        } else if (info.file.status === 'error') {
          this.$message.error(`文件上传失败: ${info.file.msg} `);
        }
        this.fileList = fileList
      },


       conversiontime(timestamp) {
          var date = new Date(timestamp);
          var Y = date.getFullYear() + '-';
          var  M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
          var D = (date.getDate()<10?'0'+(date.getDate()):date.getDate()) + ' ';
          var h = (date.getHours()<10?'0'+(date.getHours()):date.getHours()) + ':';
          var m = (date.getMinutes()<10?'0'+(date.getMinutes()):date.getMinutes())+':';
          var s = (date.getSeconds()<10?'0'+(date.getSeconds()):date.getSeconds());
          return Y+M+D+h+m+s;
      },



      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);
      },
      handleCancel () {
        this.close()
      },
      // 获取用户选择企业提交的返回数据
      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);
      },
      handleCancel () {
        this.close()
      },
      // 获取用户选择服务商弹提交的返回数据
      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;
  }
  .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>