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

        <a-form-item label="付款企业" :labelCol="labelCol" :wrapperCol="wrapperCol">
             {{model.companyName}}
        </a-form-item>
        <a-form-item label="通过平台" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <template v-if="model.isThroughPlatform==1">是&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 请上传平台与服务商之间的发票</template>
          <template v-else="">否&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;请上传企业与服务商之间的发票</template>
        </a-form-item>
        <a-form-item label="服务商" :labelCol="labelCol" :wrapperCol="wrapperCol">
          {{model.subcontractorName}}
        </a-form-item>
        <a-form-item label="发票金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
          ￥{{model.totalPayment}}
        </a-form-item>
        <a-form-item label="发票号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['invoiceNumber', validatorRules.invoiceNumber]" placeholder="请输入发票号"></a-input>
        </a-form-item>

        <a-form-item label="发票照片" :labelCol="labelCol" :wrapperCol="wrapperCol" :required="true">
          <a-upload
            listType="picture-card"
            class="avatar-uploader"
            :action="uploadAction"
            :data="{'isup':1,'bizPath':'/hlwInvoice/invoice'}"
            :headers="headers"
            :file-list="fileList"
            :beforeUpload="beforeUpload"
            @change="handleChange"
          >
            <div>
              <a-icon :type="'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>

          </a-upload>
        </a-form-item>




      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import Vue from 'vue'
  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JDate from '@/components/jeecg/JDate'
  import JImageUpload from '../../../components/jeecg/JImageUpload'
  import { ACCESS_TOKEN } from "@/store/mutation-types"


  export default {
    name: "HlwInvoiceModal",
    components: { 
      JDate,
      JImageUpload
    },
    data () {
      return {
        canClick:true,
        headers:{},
        fileList: [],
        uploadLoading: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 },
        },
        confirmLoading: false,
        validatorRules: {
          invoiceNumber: {
            rules: [
              { required: true, message: '请输入发票号!'},
            ]
          },
          invoice: {
            rules: [
              { required: true, message: '请输入发票凭证（多图以分号区分）（此字段为空代表未开票，不为空代表已开票）!'},
            ]
          },

        },
        url: {
          add: "/wisdom/hlwInvoice/add",
          fileUpload: window._CONFIG['domianURL']+"/hpSys/common/ossUpload",
          imgerver: window._CONFIG['imgDomainOssURL'],
        }
      }
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token":token}
    },
    computed:{
      uploadAction:function () {
        return this.url.fileUpload;
      }
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
      this.canClick=true
        this.fileList=[]
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'amount','invoiceNumber','invoice','sysOrgCode','uploadTime','uploadBy'))
        })
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        if(this.fileList.length==0){
          this.$message.warning("请上传发票照片");
          return
        }
        if(!this.canClick){
          this.$message.warning("请等待发票上传成功后再提交");
          return
        }
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            httpurl+=this.url.add;
            method = 'post';
            let formData = {}
            //多图
            let path = '';
            let arr = []
            for (var a = 0; a < this.fileList.length; a++) {
              arr.push(this.fileList[a].response.message)
            }
            if (arr.length > 0) {
              path = arr.join(',')
            }
            formData.invoice = path;
            formData.amount=this.model.totalPayment
            formData.invoiceNumber=this.form.getFieldValue("invoiceNumber")
            formData.idsList = this.model.idsList;
            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()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'amount','invoiceNumber','invoice','sysOrgCode','uploadTime','uploadBy'))
      },

      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)
      },
      beforeUpload: function(file){
        var fileType = file.type;
        if(fileType.indexOf('image')<0){
          this.$message.warning('请上传图片');
          return false;
        }
        //TODO 验证文件大小
      },
      handleChange (info) {
        this.canClick=false
        console.log('--文件列表改变--',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;
              }
              return file
            })
          }
          this.$message.success(`${info.file.name} 上传成功!`)
          this.canClick=true
        } 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
        if (info.file.status === 'done' || info.file.status === 'removed') {
          this.handlePathChange()
        }
      },

      handleDelete(file) {
        //如有需要新增 删除逻辑
        const index = this.fileList.indexOf(file);
        const newFileList = this.fileList.slice();
        newFileList.splice(index, 1);
        this.fileList = newFileList;
      },

      
    }
  }
</script>