<template>
  <a-modal
    :title="title"
    :width="width"
    :bodyStyle="bodyStyle"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="服务商" :labelCol="labelCol" :wrapperCol="wrapperCol">
          {{model.subcontractorName}}
        </a-form-item>
        <a-form-item label="完税金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
          {{model.amount}}
        </a-form-item>
        <a-form-item label="发票号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="[ 'receiptNumber', validatorRules.receiptNumber]" placeholder="请输入发票号" style="width: 100%"/>
        </a-form-item>
        <a-form-item label="完税照片" :labelCol="labelCol" :wrapperCol="wrapperCol"  :required="true">
          <a-upload
            listType="picture-card"
            :fileList="fileList"
            class="avatar-uploader"
            :action="uploadAction"
            :data="{'isup':1,'bizPath':bizPath}"
            :headers="headers"
            @preview="handlePreview"
            :beforeUpload="beforeUpload"
            @change="handleChange"
            >
            <a-icon :type="'plus'" />
            <div class="ant-upload-text">上传</div>

          </a-upload>
        </a-form-item>
      </a-form>
      <HlwPictureModal ref="modalSelectRequireForm"></HlwPictureModal>
    </a-spin>
  </a-modal>
</template>

<script>

  import { httpAction,getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import JDate from '@/components/jeecg/JDate'
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import HlwPictureModal from '../modules/HlwPictureModal'

  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: 'HlgPaymentTaxModal',
    components: {
      JDate,
      HlwPictureModal
    },
    data() {
      return {
        form: this.$form.createForm(this),
        title: '操作',
        width: 800,
        bodyStyle: {
          paddingTop: '20px',
          paddingBottom:'50px',
          maxHeight: (window.innerHeight * 0.47) + 'px',
          'overflow-y': 'auto'
        },
        visible: false,
        model: {},
        headers:{},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        picUrl: '',
        id: '',//完税申请id
        uploadLoading: false,
        confirmLoading: false,
        validatorRules: {
          receiptNumber: { rules: [{ required: true, message: '请输入发票号!' }] },
          taxPaymentReceipt: { rules: [{ required: true, message: '请上传完税证明!' }] },
        },
        url: {
          taxPayment: '/wisdom/hlwDutyPaid/taxPayment',
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
          imgerver: window._CONFIG['imgDomainOssURL']
        },
        //多图上传属性
        previewVisible: false,
        previewImage: '',
        fileList: [],
      }
    },
    props: {
      /*这个属性用于控制文件上传的业务路径*/
      bizPath: {
        type: String,
        required: false,
        default: '/hlwinvoice/hlwduty'
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }
    },
    computed: {
      uploadAction: function() {
        return this.url.fileUpload
      }
    },
    methods: {
      add(record, ids) {
        this.edit(record,ids)
      },
      edit(record,ids) {
        this.fileList = []
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.id = ids;
        this.visible = true
      },
      close() {
        this.$emit('close');
        this.visible = false
      },
      handleOk() {
        const that = this
        if (this.fileList.length == 0) {
          that.$message.warning('请上传完税证明！')
          return
        }
        const { fileList } = that;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
              that.confirmLoading = true;
              let httpurl = that.url.taxPayment;
              let method = 'put';
              let formData = Object.assign({}, values);
              formData.ids = that.id;
              formData.totalAmount = that.model.amount;
              //图片上传是否完成
              let isDone = true;
              let path = '';
              let arr = []
              fileList.forEach((file,index) => {
                if(!file.thUrl){
                  isDone = false;
                }
                arr.push(file.thUrl)
              });
              if (arr.length > 0) {
                path = arr.join(',')
              }
              //上传文件出错
              if(!isDone){
                that.$message.error("正在上传，请稍后提交!");
                that.confirmLoading = false
                return;
              }
              formData.taxPaymentReceipt = path;
              console.log("表单提交数据",formData)
              httpAction(httpurl,formData,method).then((res)=>{
                if(res.success){
                  that.$message.success(res.message);
                  that.$emit('ok');
                  that.close();
                }else{
                  that.$error({
                    title: '失败',
                    content: res.message,
                    okText: '确定',
                    centered: true,
                    onOk: () => {

                    }
                  })
                }
              }).finally(() => {
                that.confirmLoading = false;
              })
          }
        })
      },
      handleCancel() {
        this.close()
      },
      beforeUpload: function(file) {
        var fileType = file.type
        if (fileType.indexOf('image') < 0) {
          this.$message.warning('请上传图片')
          return false
        }
        //TODO 验证文件大小
      },
      handleChange(info) {
        console.log('--文件列表改变--',info)
        let fileList = info.fileList
        if (info.file.status === 'done') {
          var response = info.file.response
          console.log(response)
          if (response.success) {
            fileList = fileList.map((file) => {
              if (file.response) {
                file.url = this.url.imgerver +file.response.message;
                file.thUrl = file.response.message;
              }
              return file
            })
            this.$message.success(`${info.file.name} 上传成功!`)
          } else {
            this.$message.warning(response.message)
          }
        }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
      },
      handleDelete(file) {
        //如有需要新增 删除逻辑
        const index = this.fileList.indexOf(file);
        const newFileList = this.fileList.slice();
        newFileList.splice(index, 1);
        this.fileList = newFileList;
      },
      getAvatarView() {
        return this.url.imgerver + this.model.taxPaymentReceipt
      },
      //预览图片
      handlePreview(file) {
        var idcard = [];
        var previewImage = file.url || file.thumbUrl;
        idcard.push(previewImage);
        this.$refs.modalSelectRequireForm.edit(idcard)
        this.$refs.modalSelectRequireForm.title = ''
        this.$refs.modalSelectRequireForm.disableSubmit = false
      },
    }
  }
</script>
<style lang="less" scoped>
  .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>
