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

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


        <a-form-item label="账户余额" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <span style="color: #2eabff">{{balance}}</span>
        </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>

        <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>
  </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'
  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: {
      CompanySelectWindow,
      HwPaymentExportErrorModal,
      JDate,
      JUpload,
      JSelectDepart,
      JDictSelectTag
    },
    data() {
      return {
        balance:0.00,
        selectedDepartKeys1:[], //保存用户选择企业id
        checkedDepartKeys1:[],
        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: 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?companyId=",
          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.balance=0.00
        this.model={}
        this.fileList=[]
        this.form.resetFields()
        this.model = record
        console.log(666666,record)
        this.visible = true
        this.showUploadList = false;
        this.selectedDepartKeys1 = [];
        this.checkedDepartKeys1 = [];
        this.companyId=0
        //查询余额
        getAction(this.url.queryBalance,{}).then((res)=>{
          this.balance=res
        });
      },
      close() {
        this.$emit('ok')
        this.visible = false
      },
      handleOk() {
        this.$emit('ok')
        this.visible = false
      },
      handleCancel() {
        this.close()
      },
      popupCallback(row) {

      },

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

      /* 导入 */
      handleImportExcel2(info){
        this.showUploadList = true;
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        let fileList = info.fileList
        if (info.file.status === 'done') {
          if(info.file.response.success){
            this.type=2
            this.$message.success(`${info.file.name} 文件上传成功`);
          } 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
            }
            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];

          getAction(this.url.queryBalance,{companyId:this.companyId}).then((res)=>{
              console.log(4444,res)
                 this.balance=res
          });

        }
      },


    }
  }
</script>