<template>
  <div>
    <Base-dialog
      title="导入"
      width="660px"
      :isShow.sync="isShow"
      :isShowFooter="false"
    >
      <div>
        <div class="swq">
          <img
            style="width: 182px; height: 168px"
            src="@/assets/images/dr.png"
            alt=""
          />
        </div>
        <div style="padding-left: 100px">
          <p>第一步：下载导入模板</p>
          <p style="padding-left: 50px">
            <i class="el-icon-upload"></i
            ><span class="dowmStys" @click="getDowm">下载模板</span>
          </p>
          <p>第二步：(批量新增)：点击“上传{{ type }}”完成导入</p>
          <div
            v-loading="loading"
            element-loading-text="正在处理中"
            style="margin: 0 0 20px 50px; width: 130px; height: 60px"
          >
            <label
              v-show="!loading"
              for="mobles"
              class="el-button el-button--primary"
              >上传 {{ type }}</label
            ><input
              style="display: none"
              type="file"
              id="mobles"
              ref="input1"
              @change="importMobleadd"
            />
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShow = false">取消</el-button>
        </span>
      </div>
    </Base-dialog>
    <Base-dialog
      title="提示"
      width="660px"
      :isShow.sync="isShowErr"
      :isShowFooter="false"
    >
      <div>
        <div>
          <h4 style="margin-top: 0px; font-weight: bold; text-align: center">
            导入失败原因
          </h4>
          <el-input
            readonly
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 24 }"
            v-model="errorData"
          >
          </el-input>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShowErr = false">确定</el-button>
        </span>
      </div>
    </Base-dialog>
  </div>
</template>

<script>
import * as baseUrls from "@/utils/request.js";
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    temUrl: {
      type: String,
    },
    apiKey: {
      type: String,
    },
    checkKey: {
      type: String,
    },
    newSujectApis: {
      type: Array,
      default: () => {
        return [];
      },
    },
    isCheck: {
      type: Boolean,
      default: true,
    },
    isShowTip: {
      type: Boolean,
      default: true,
    },
    param: {
      type: Object,
      default: () => {
        return {};
      },
    },
    type: {
      type: String,
      default: "Excel",
    },
    isSuccessBack: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      errorData: [],
      isShowErr: false,
    };
  },
  methods: {
    getDowm() {
      let url =
        baseUrls.BASE_IMG_URL +
        this.temUrl +
        `?time=${this.$methodsTools.getNewTime()}`;
      let link = document.createElement("a");
      let fileName = "导入模板" + ".xlsx";
      document.body.appendChild(link);
      link.href = url;
      link.dowmload = fileName;
      link.click();
      link.remove();
    },
    importMobleadd(e) {
      var file = e.target.files[0];
      if (file === undefined) {
        e.target.value = "";
        return;
      }
      var type = e.target.value.toLowerCase().split(".").splice(-1);
      if (this.type == "Excel") {
        if (type[0] != "xlsx" && type[0] != "xls") {
          e.target.value = "";
          this.$message.error("请上传excel文件,且上传格式需为：.xlsx、.xls");
          return;
        }
      } else {
        if (type[0] != "docx") {
          e.target.value = "";
          this.$message.error("请上传word文件,且上传格式需为：.docx");
          return;
        }
      }
      this.loading = true;
      let formData = new FormData();
      formData.append("file", file);
      for (const key in this.param) {
        formData.append(key, this.param[key]);
      }
      this.$api[this.apiKey](formData)
        .then((res) => {
          if (res.code === 200) {
            this.isCheck && this.getFestivalList(res.data);
            this.getErrorData(res.data || res);
          }
        })
        .finally(() => {
          e.target.value = "";
          this.loading = false;
        });
    },
    /**
     *
     * @param {Strings} ids 查询编码
     * @param {Number} type 1为成功2为失败
     * @remards 失败时也需查询是否有成功的数据导入数据库，如存在 则加列队列同时提示
     */
    getFestivalList({ importNo, errorLog }) {
      this.$api[this.checkKey]({ importNo })
        .then((res) => {
          if (res.rows.length) {
            errorLog &&
              this.$message({
                type: "success",
                message: `成功导入${res.rows.length}条数据,`,
                customClass: "myMessageClass",
              });
            this.$emit("success", res.rows);
          }
        })
        .catch(() => {});
    },
    getErrorData(data) {
      this.isShow = false;
      let { errorLog } = data;
      if (errorLog) {
        let ary = errorLog.split("\r\n");
        ary = ary
          .filter((item) => {
            return item.length > 0;
          })
          .reverse();
        this.$message({
          message: `${ary.length}条数据导入失败,请查看失败原因`,
          customClass: "myMessageClass",
        });
        ary = ary.join("\r\n");
        this.errorData = ary;
        this.isShowErr = true;
      } else {
        this.isShowTip &&
          this.$message({
            type: "success",
            message: `添加成功`,
            customClass: "myMessageClass",
          });
      }
      if (!errorLog || this.isSuccessBack) {
        this.$emit("success", data);
      }
    },
  },
  computed: {
    isShow: {
      get() {
        return this.dialogVisible;
      },
      set(val) {
        this.$emit("update:dialogVisible", false);
      },
    },
  },
};
</script>

<style  lang="less" scoped>
.swq {
  text-align: center;
  border-bottom: 1px solid #eee;
}
.dowmStys {
  color: blue;
  cursor: pointer;
}
/deep/.el-dialog {
  .el-dialog__body {
    padding: 30px 20px 0;
  }
  .dialog-footer {
    height: 80px;
    border-top: 1px solid #e2e2e2;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}
</style>