<template>
  <a-button :disabled="disabled" :icon="icon" :size="size" :type="type" @click.stop="handleClick">
    <slot />
    <p-modal v-model="visible" okText="导入" :title="label" :maskClosable="false" :confirmLoading="loading" @ok="handleFormUpload" @cancel="handleCancel">
      <p-grid-form ref="form" name="formImport" style="padding-bottom: 20px" :span="24" :labelCol="{ span: 6 }">
        <p-grid-form-item :name='fileKey' label='导入文件'>
          <a-upload  :showUploadList="false" :file-list="fileList" :beforeUpload="handleChange" accept=".xls,.xlsx">
            <p-input readOnly style="width:346px" :value="fileName">
              <a-icon slot="prefix" type="upload" />
            </p-input>
          </a-upload>
      </p-grid-form-item>
       <p-grid-form-item v-bind="itemSelect">
        <p-button slot="unit" type="primary" :icon="downloadLoad ? 'loading' : 'cloud-download'" @clickSync="download">模板下载</p-button>
      </p-grid-form-item>
      </p-grid-form>
    </p-modal>
  </a-button>
</template>
<script>
import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE } from '@/config/serviceSettings.js';

export default {
  name: 'PImportExcel',
  props: {
    downloadFileName: '',
    radio: {
      type: Boolean,
      default: false,
    },
    label: {
      type: String,
      default: '',
    },
    tmpUrl: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    icon: {
      type: String,
      default: 'cloud-upload',
    },
    size: {
      type: String,
    },
    type: {
      type: String,
      default: 'primary',
    },
    fileKey: {
      type: String,
      default: 'file',
    },
    remoteUrl: {
      type: String,
      default: '',
    },
    beforeUpload: {
      type: Function,
      default: null,
    },
    formItmes: {
      type: Array,
      default: null,
    },
  },

  data() {
    return {
      downloadLoad: false,
      fileName: '选择上传文件',
      loading: false,
      visible: false,
      itmes: null,
      fileList: [],
      file:  {
          name: this.fileKey,
          label: '导入文件',
          scopedSlots: { customRender: 'file' },
        },
      itemSelect:{
        type: 'select',
        style: 'margin-top:10px',
        name: 'templateId',
        wrapperCol: { span: 17 },
        value: undefined,
        label: '模板导入',
        required: true,
        options:[]
     },
    };
  },

  watch: {
    // formItmes: {
    //   immediate: true,
    //   handler(formItmes) {
    //     if (!formItmes) return;

    //     let obj = {
    //       name: this.fileKey,
    //       label: '导入文件',
    //       scopedSlots: { customRender: 'file' },
    //     };
    //     this.itmes = [obj, ...this.formItmes];
    //   },
    // },
  },

  computed: {
    // isSingle() {
    //   return !this.formItmes || this.formItmes.length == 0 || this.formItmes.every((tt) => tt.hidden);
    // },
  },
  mounted() {
    this.getQuery()
  },

  methods: {
    getQuery() {
      this.axios.post(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/sysimport/templet/listPage',
        { pageNum: 1, pageSize: 9999, importObjNo: 'SHIPBILL_IMPORT', status: 1 }).then(res => {
          if (res.success && res.data?.list?.length > 0) {

            this.itemSelect.options = res.data.list.map(item => {
              return {
                label:item.templeteName,
                value: item.id
              }
            })
          }

        });
    },
    download(event) {
      event.preventDefault();
      this.$refs.form.form.validateFieldsAndScroll((errors, values) => {
        if (errors) return;
        let data = {
          templateId: values.templateId,
        };
        this.downloadLoad = true;
        this.axios({
          url: this.tmpUrl,
          method: 'post',
          responseType: 'blob',
          data,
          timeout: 36000000,
        })
          .then((response) => {
            this.downloadLoad = false;
            let downloadElement = document.createElement('a');
            let href = window.URL.createObjectURL(response); //创建下载链接
            let fileName = '文件模板';
            if (this.downloadFileName) {
              fileName = this.downloadFileName + '.xls';
            }
            downloadElement.href = href;
            downloadElement.download = decodeURIComponent(fileName); //解码
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement);
            window.URL.revokeObjectURL(href); //
          })
          .catch((error) => {
            this.downloadLoad = false;
            this.$exception(error);
          });
      });
    },

    handleClick(event) {
      // if (this.isSingle) {
      //   this.$refs.file.click();
      // } else {
      //   this.visible = true;
      // }
      this.visible = true;

    },

    handleChange(info) {
      this.fileName = '../' + info.name;
      this.fileList = [info];
      return false;
    },

    handleUpload(e) {
      let files = e.target.files;
      if (files.length == 0) {
        return;
      }
      let formData = new FormData();
      formData.append(this.fileKey, files[0]);
      let data = formData;
      if (this.beforeUpload) {
        data = this.beforeUpload(formData);
      }
      this.loading = true;
      // reset
      e.target.value = '';
      this.handleHttp(data);
    },

    handleCancel() {
      this.$refs.form.form.resetFields();
      this.fileList = [];
      this.fileName = '选择上传文件';
    },

    handleFormUpload() {
      if (this.fileList.length == 0) return;

      this.$refs.form.form.validateFields((err, vals) => {
        if (err) return;
        let formData = new FormData();
        console.log(vals);
        formData.append(this.fileKey, this.fileList[0]);
        Object.keys(vals).forEach((k) => {
          if (k == this.fileKey) return;
          formData.append(k, vals[k]);
        });
        let data = formData;
        if (this.beforeUpload) {
          data = this.beforeUpload(formData);
        }
        this.loading = true;
        this.handleHttp(data);
      });
    },

    handleHttp(data) {
      this.axios({
        url: this.remoteUrl,
        method: 'post',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        data: data,
        timeout: 36000000,
      })
        .then((response) => {
          this.loading = false;
          if (response.success) {
            this.$message.success(response.message);
            this.visible = false;
            this.handleCancel();
            this.$emit('onSubmit', response);
          } else {
            this.$exception(response);
            this.$emit('onSubmitError', response);
          }
        })
        .catch((error) => {
          this.loading = false;
          this.$exception(error);
          this.$emit('onSubmitError', error);
        });
    },
  },
};
</script>
