<template>
  <div>
    <Modal
      v-model="modalVisible"
      :title="completeTitle"
      :mask="true"
      :closable="true"
      :mask-closable="false"
      :width="width"
      class="importDialogAddOther"
      @on-cancel="closeDialog"
    >
      <div>
        <div
          v-if="tablename == 'V_IES_PRODUCT'"
          class="importForm"
        >
          <Form
            ref="formModel"
            :model="formModel"
            :rules="ruleValidate"
            :label-width="75"
            label-position="left"
          >
            <FormItem
              label="组合类型:"
              prop="accountType"
            >
              <Select
                v-model="formModel.accountType"
                filterable
                clearable
                @on-change="changeType"
              >
                <Option
                  v-for="item in accountTypeList"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.label }}
                </Option>
              </Select>
            </FormItem>
          </Form>
        </div>
        <div class="import-panel">
          <div class="upload-panel">
            <span style="display: inline-block;width: 75px;">文件:</span><Button
              type="posdefault"
              :size="buttonSize"
            >
              选择文件
            </Button>
            <!-- name -->
            <input
              id="file"
              class="fileInput"
              type="file"
              accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
              @change="fileChange($event)"
            >
            <!-- @click="clearFile" -->
            <!-- <div
              class="tip"
            >
              {{ ChineseDictionary.FILEMAX }}{{ fileSizeNumber }}
            </div> -->
            <div
              v-if="fileName"
              class="tip fileName"
            >
              已选择：<span class="chooedFile">{{ fileName }}</span>
            </div>
          </div>
          <transition name="fade">
            <span v-if="loading">数据正在导入中，请稍候</span>
          </transition>
          <div class="el-upload__tip" style="line-height:18px;" >
            注意：{{ ChineseDictionary.IMPORTTITLE }}
            <a
              @click.stop="downloadTemplate"
            >{{ ChineseDictionary.DOWNTEMPLATE }}</a>
          </div>
        </div>
      </div>
      <div slot="footer">
        <div>
          <Button
            type="fcdefault"
            :disabled="loading"
            :size="buttonSize"
            @click="submitUpload()"
          >
            {{ ChineseDictionary.IMPORT }}
          </Button>

          <Button
            type="fcdefault"
            :size="buttonSize"
            @click.stop="closeDialog(false)"
          >
            {{ ChineseDictionary.CANCEL }}
          </Button>
        </div>
        <div
          v-if="errorMsg.errorList.length>0"
          class="error-content"
        >
          <div class="error-message">
            <div class="left-icon">
              <i class="iconfont">&#xecd0;</i>
            </div>
            <div class="right-content">
              <p
                v-if="errorMsg.errorUrl.length > 0"
                class="link"
              >
                <a :href="errorMsg.errorUrl">（下载报错信息）</a>
              </p>
              <div class="content-message">
                <p class="title">
                  {{ errorMsg.message }}
                </p>
                <p
                  v-for="(msg,index) in errorMsg.errorList"
                  :key="index"
                >
                  <span v-if="msg.rowIndex&&!(tablename=='V_IES_PRODUCT'||tablename=='T_IESSkuGroupDetail')">第{{ msg.rowIndex }}条记录报错:</span>
                  {{ msg.message }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
  import axios from 'axios';
  // import ChineseDictionary from '../assets/js/ChineseDictionary';
  // import network, { urlSearchParams, getGateway } from '../__utils__/network';
  import Upload from '../../assets/js/upload';

  import { DispatchEvent, R3_IMPORT } from '../../assets/js/__utils__/dispatchEvent';

  const R3 = window.R3;

  const { network, urlSearchParams } = R3;

  export default {
    name: 'ImportDialog',
    props: {
      // name: {
      //   type: Boolean,
      //   default: false
      // },
      customImport: {
        type: Boolean,
        default: false
      }, // 自定义导入接口
      fatherMethod: {
        type: Function,
        default: null
      },
      visible: {// 是否打开弹框
        // 显示
        type: Boolean,
        default: false
      },
      title: {// 弹框title
        // 标题
        type: String,
        default: ''
      },
      combinedCommoditySku: {// 福袋商品对应虚拟条码
        type: String,
        default: ''
      },
      tablename: {// /p/cs/downloadImportTemplate 用于下载模版,上传文件参数
        // 子表名
        type: String,
        default: ''
      },
      mainTable: {// 用于/p/cs/import参数上传文件
        // 主表名
        type: String,
        default: ''
      },
      mainId: {// 用于/p/cs/import参数上传文件
        // 主表id
        type: [Number, String],
        default: -1
      },
      width: {// 当前弹框参数
        // 宽度
        type: String,
        default: '630'
      },
      accountList: {
        // 宽度
        type: Array,
        default: () => []
      }
    },
    components: {},
    data() {
      return {
        accountTypeList: [ // 组合商品类型
          {
            label: '普通类型',
            value: 1
          },
          {
            label: '福袋类型',
            value: 2
          },
        ],
        inputValue: '2', // 有效起始行
        singleValue: '', // 更新记录
        modalVisible: false,
        showFlag: false,
        loading: false, // 是否加载
        ChineseDictionary: {
          IMPORTTITLE: '上传文件中，不要放置宏或图标，不要更改列的顺序，数据中不要使用公式。',
          IMPORT: '导入',
          CANCEL: '取消',
          DOWNTEMPLATE: '(下载模版)',
          FILEMAX: '文件最大'
        },
        fileSizeNumber: '',
        fileSize: '', // 文件尺寸
        importFlies: [], // 导入文件列表
        errorMsg: {
          // 错误信息
          errorUrl: '',
          message: '',
          errorList: []
        },
        files: [],
        buttonSize: 'small',
        fileName: '',

        // 财务对账
        formModel: {
          accountType: '',
          account: ''
        },
        ruleValidate: {
          accountType: [
            { required: true, message: '', trigger: 'blur' }
          ],
        }
      };
    },
    watch: {
      modalVisible: {
        handler(val) {
          if (!val) {
            this.$emit('closeDialog');
          }
        }
      },
      visible: {
        handler(val) {
          if (val) {
            this.modalVisible = true;
          } else {
            this.modalVisible = false;
          }
        }
      }
    },
    mounted() {
      if (this.visible) this.modalVisible = true;
      else this.modalVisible = false;
      this.axiosSetting();
    },

    computed: {
      completeTitle() {
        let name = '';
        name = '导入组合商品类型';
        return name;
      },
      inpNum() {
        return this.inputValue;
      }
    },

    methods: {
      changeType() {
        console.log(this.formModel.accountType);
      },
      getGateway(str) {
        return `${str}`;
      },
      clearFile() {
        this.fileName = '';
        this.loading = false;
        this.files = [];
        const fileDom = document.getElementById('file');
        fileDom.value = '';
      },
      fileChange(e) {
        this.errorMsg = {
          // 错误信息
          errorUrl: '',
          message: '',
          errorList: []
        };
        this.files = e.target.files[0];
        this.fileName = e.target.files[0].name;
        this.fileSize = e.target.files[0].size;
      },
      // 发送请求, 获取上传参数
      axiosSetting() {
        network.post('/p/cs/settings',
                     urlSearchParams({
                       configNames: JSON.stringify(['upload.import.max-file-size'])
                     })).then((res) => {
          if (res.data.code === 0) {
            this.fileSizeNumber = res.data.data['upload.import.max-file-size'];
          } else this.fileSizeNumber = '0M';
        })
          .catch((error) => {
            if (error.response.status === 403) {
              this.closeDialog();
            }
            this.fileSizeNumber = '0M';
          });
      },
      // 发送请求, 下载模板
      downloadTemplate() {
        if (this.customImport) {
          if (this.tablename == 'V_IES_PRODUCT') { 
            const link = document.createElement('a');
            link.style.display = 'none';
            if (!this.formModel.accountType) {
              return this.$Message.warning('请先选择组合类型！');
            }
            // 组合商品(商品-->组合商品（普通类型、福袋类型）)
            if (this.formModel.accountType == 1) {
              link.href = '../../../static/importExcel/普通组合商品导入模板.xlsx';
              link.setAttribute('download', '普通组合商品导入模板.xlsx');
            } else if (this.formModel.accountType == 2) {
              link.href = '../../../static/importExcel/福袋商品导入模板.xlsx';
              link.setAttribute('download', '福袋商品导入模板.xlsx');
            }
            document.body.appendChild(link);
            link.click();
          }
        }
      },
      // 提交上传文件请求
      submitUpload() {
        if (this.formModel.accountType == '' || !this.formModel.accountType) {
          return this.$Message.warning('请先选择组合类型！');
        }
        if (this.files.length === 0) {
          return this.$Modal.fcWarning({
            title: '警告',
            mask: true,
            content: '请先选择要导入的文件！'
          });
        }
        this.uploadFileChange();
      },
      uploadFileChange() {
        this.errorMsg = {
          // 错误信息
          errorUrl: '',
          message: '',
          errorList: []
        };
        this.loading = true;
        // 上传文件
        const fileInformationUploaded = this.files;
        // this.$R3loading.show();
        // debugger;
        let url = '';
        let aUploadParame;
        let sendData;
        if (this.customImport) {
          if (this.tablename == 'V_IES_PRODUCT') { // 组合类型导入
            url = `${this.getGateway('/p/cs/combinedCommodity/batch/common')}`;
          }
          if (this.formModel.accountType == 1) {
            sendData = {
              isLuckyBag: false
            }; 
          } else if (this.formModel.accountType == 2) {
            sendData = {
              isLuckyBag: true
            };
          }
        }
        aUploadParame = Object.assign(
          {},
          {
            target: fileInformationUploaded,
            url,
            sendData,
            imgSize: this.fileSize,
            success: this.handleSuccess,
            onerror: this.handleError,
            onloadstart: this.onloadstart,
            type: 'file'

          }
        );
        const article = new Upload(aUploadParame);
      },
      // 上传成功
      handleSuccess(response) {
        const { tableName } = this.$route.params;
        if (response.code === 0) {
          this.$R3loading.hide(tableName);
          this.closeDialog();
          this.fileName = '';
          this.$Modal.fcSuccess({
            title: '成功',
            mask: true,
            content: response.message
          });
          this.$emit('importantSuccess');
          if (this.tablename == 'T_IESSkuGroupDetail') {
            this.$emit('jumpPage'); // 福袋商品导入成功跳转编辑页面
          }
          const asyncTaskScheme = () => (window.ProjectConfig && window.ProjectConfig.asyncTaskScheme ? window.ProjectConfig.asyncTaskScheme : '');  // 异步导出设计方案
          if(asyncTaskScheme() === 'skq') {
            const params = {
              detail: {
                type: 'notice'
              }
            }
            DispatchEvent(R3_IMPORT, params)
            this.$R3loading.hide(this.loadingName);
            this.closeDialog()
            return
          }
        } else {
          this.$R3loading.hide(tableName);
          if (response.data) {
            if (response.data.path) {
              if (response.data.path === 'undefined ===') {
                this.errorMsg.errorUrl = '';
              } else {
                const gatewayth = this.getGateway('/p/cs/download?filename');
                this.errorMsg.errorUrl = this.urlChange(`${gatewayth}=${
                  response.data.path
                }`);
              }
            }
            this.errorMsg.errorList = response.data.error || [
              { rowIndex: 0, message: '' }
            ];
          } else {
            this.errorMsg.errorList = response.error || [
              { rowIndex: 0, message: '' }
            ];
          }
          this.errorMsg.message = response.message;
          // this.$Modal.fcWarning({
          //   title: '警告',
          //   mask: true,
          //   content: response.message
          // });
          this.clearFile();
        }
        this.$emit('confirmImport');
        
      },
      urlChange(url) { // 对下载的url地址进行转换，处理特殊字符
        const arr = url.split('/');
        let [last] = [...arr].reverse();
        last = encodeURIComponent(last);
        arr[arr.length - 1] = last;
        return arr.join('/');
      },
      // 上传失败
      handleError(e) {
        const { tableName } = this.$route.params;
        this.$R3loading.hide(tableName);
        const emg = e;
        let formatJsonEmg = null;
        try {
          formatJsonEmg = JSON.stringify(JSON.parse(emg), null, 4);
        } catch (v) {
          if (typeof emg === 'string') {
            formatJsonEmg = emg.replace(/<br\/>/g, '\r\n');
          }
        }
        window.vm.$Modal.fcError({
          mask: true,
          titleAlign: 'center',
          title: '错误',
          render: h => h('div', {
            style: {
              padding: '10px 20px 0',
              display: 'flex',
              lineHeight: '16px'
            }
          }, [
            
            h('i', {
              props: {
              },
              style: {
                marginRight: '5px',
                display: 'inline-block',
                'font-size': '28px',
                'margin-right': ' 10px',
                'line-height': ' 1',
                padding: ' 10px 0',
                color: 'red'
              },
              class: 'iconfont iconbj_error fcError '
            }),
            h('div', {
              style: `width: 80%;
                  margin: 1px;
                  margin-bottom: -8px;
                  box-sizing: border-box;
                  padding: 5px;
                  resize: none;
                  max-height: 100px;
                  max-width: 300px;
                  overflow: auto;
                  `
            }, formatJsonEmg)
          ])
        });
        this.clearFile();
        this.closeDialog();
      },
      closeDialog() {
        this.modalVisible = false;
        this.fatherMethod();
        if (this.tablename == 'V_IES_PRODUCT') {
          this.clearFile();
          this.errorMsg = {
            // 错误信息
            errorUrl: '',
            message: '',
            errorList: []
          };
        }
      },
      ToNewAccount() {
        this.closeDialog();
        window.parent.R3.store.commit('global/tabOpen', {
          type: 'V',
          tableName: 'T_OMSBANKINFO',
          tableId: '10706',
          id: 'New',
          dynamicRoutingForCustomizePage: true
        });
      }
    }
  };
</script>
<style lang="less">
.importDialogAddOther {
  .ark-select-single .ark-select-selection {
    height: 32px;
  }
  .ark-form-item {
    margin-bottom: 10px;;
  } 
  .chooedFile {
    color: #2D8cF0;
  }
  .ToNewAccount {
    cursor: pointer;
    color: #2D8cF0;
  }
  .importICon {
    margin: 0;
    text-align: center;
    .icon-span {
      display: inline-block;
      height: 28px;
      width: 28px;
      i {
        color: #09a155;
        font-size: 28px;
      }
    }
  }
  .importForm {
    padding: 0 40px;
  }
  .import-panel {
    padding: 0 40px;
    position: relative;
    .el-upload__tip {
      margin-top: 10px;
      font-size: 12px;
      color: #575757;
      .inputValue{
        border: none;
        border-bottom: 1px solid #b8b8b8;
        text-align: center;
        width: 100px;
      }
      .singleValue{
        margin-left:10px;
      }
    }
    .upload-panel {
      height: 30px;
      // margin-top: 24px;
    }
    .fileName {
      height: 21px;
      line-height: 21px;
      color: #606266;
    }
  }
  .fileInput {
    position: relative;
    left: -67px;
    opacity: 0;
    width: 62px;
  }
  .tip {
    font-size: 12px;
    display: inline-block;
    margin-left: -61px;
    color: #b8b8b8;
  }
  .error-content {
    border-top: solid 1px #bcbcbc;
    text-align: left;
    position: relative;
    font-size: 12px;
    margin-top: 10px;
    .error-message {
      height: auto;
      margin: 10px 0px;
      max-height: 240px;
      position: relative;
      width: 550px;
      .left-icon {
        height: 28px;
        width: 28px;
        position: absolute;
        left: 0;
        top: 0;
        i {
          font-size: 28px;
          color: #e80000;
        }
      }
      .right-content {
        position: relative;
        margin-left: 38px;
        .link {
          line-height: 16px;
          a {
            color: #0f8ee9;
            cursor: pointer;
            display: inline-block;
            padding-top: 6px;
            text-decoration: none;
          }
        }
        .content-message {
          max-height: 220px;
          min-height: 28px;
          overflow: auto;
          p {
            word-break: break-word;
            line-height: 16px;
            margin: 6px 0;
          }
        }
      }
    }
  }
  .ark-modal-body {
    padding: 20px !important;
  }
  .iconios-close {
    color: #999 !important;
  }
  .ark-modal-footer {
    border-top: none !important;
    padding: 0 20px 20px;
    margin: 10px 40px;
  }
  .ark-btn-fcdefault {
    height: 24px !important;
    font-size: 12px !important;
    width: 66px !important;
    padding: 0 !important;
  }
  .ark-modal-footer button > span {
    font-size: 12px;
  }
}
</style>
