<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">
          <j-date placeholder="付款时间" v-decorator="[ 'paymentTime', validatorRules.paymentTime]" :showTime="true" dateFormat="YYYY-MM-DD HH:mm:ss" :trigger-change="true" style="width: 100%" />
        </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>
    <HwPaymentFujianExportErrorModal ref="modalSelectRequireForm"  @ok="modalFormOk"></HwPaymentFujianExportErrorModal>
    <CompanySelectFujianWindow ref="companyWindow" @ok="modalFormOk1"></CompanySelectFujianWindow>
  </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 HwPaymentFujianExportErrorModal from './HwPaymentFujianExportErrorModal'
  import CompanySelectFujianWindow from './CompanySelectFujianWindow'
  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: {
      CompanySelectFujianWindow,
      HwPaymentFujianExportErrorModal,
      JDate,
      JUpload,
      JSelectDepart,
      JDictSelectTag
    },
    data() {
      return {
        disableSubmit:false,
        selectedDepartKeys1:[], //保存用户选择企业id
        checkedDepartKeys1:[],
        selectedDepartKeys:[], //保存用户选择服务商id
        checkedDepartKeys:[],
        companyId: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: '请选择付款企业!' }]},
          paymentTime:{ rules: [{ required: true, message: '请选择付款时间!' }]},
        },
        url: {
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
          importExcelUrl: "/hlgpaymentfujian/hlgPaymentFujian/importExcel?companyId=",
          exportXlsUrl:"/hlgpaymentfujian/hlgPaymentFujian/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
        this.visible = true
        this.showUploadList = false;
        this.selectedDepartKeys1 = [];
        this.checkedDepartKeys1 = [];
        this.companyId=0
      },
      close() {
        this.$emit('ok')
        this.visible = false
        this.selectedDepartKeys1 = [];
        this.checkedDepartKeys1 = [];
        this.companyId=0
      },
      handleOk() {
            this.$emit('ok')
            this.visible = false
      },
      handleCancel() {
        this.close()
      },
      popupCallback(row) {

      },

      importExcelUrl(){
        if(this.companyId===0){
          return
        }
        if(!this.form.getFieldValue("paymentTime")){
          return
        }
        this.model.paymentTime=this.form.getFieldValue("paymentTime")
        console.log(this.model.paymentTime)
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`+this.companyId+"&paymentTime="+this.model.paymentTime;
      },

      /* 导入 */
      handleImportExcel2(info){
        if(this.companyId===0){
          this.$message.error('请先选择付款企业');
          return
        }
        if(!this.form.getFieldValue("paymentTime")){
          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
            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];
        }
      },


      modalFormOk(){

      }


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