<template>
  <div id="index">
    <el-row>
      <el-col :span="24" style="text-align: right">
        <el-popover placement="bottom" width="370" trigger="click" style="margin-right: 10px">
          <template #reference>
            <el-button type="primary" size="mini">导入</el-button>
          </template>
          <el-upload
            class="upload-demo"
            drag
            action="/files/platform/patent_cms_import/upload"
            multiple
            :on-success="uSuccess"
            :on-error="uError"
            :before-upload="uBefore"
            :show-file-list="false"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-popover>
        <el-button type="primary" size="mini" @click="getTemplate">下载导入模板</el-button>
        <el-button type="primary" size="mini" @click="exportView">导出</el-button>
        <el-button type="primary" size="mini" @click="toResult">查看导出结果</el-button>
      </el-col>
    </el-row>
    <data-table :fields="fields" :opera="opera" :data="list" :total="total" @query="search" @view="toView">
      <template #filter>
        <filter-bar v-model="filter" @search="search"></filter-bar>
      </template>
    </data-table>
    <el-dialog title="错误记录" center :visible.sync="dialog" :destroy-on-close="true">
      <el-table border stripe :data="errorList" v-if="errcode === '1'">
        <el-table-column align="center" label="错误记录">
          <template v-slot="{ row }">{{ row }}</template>
        </el-table-column>
      </el-table>
      <el-table border stripe :data="errorList" v-if="errcode === '2'">
        <el-table-column align="center" label="发明名称" prop="name"></el-table-column>
        <el-table-column align="center" label="发明人" prop="inventor"></el-table-column>
        <el-table-column align="center" label="选择状态">
          <template v-slot="{ row }">
            {{ checkSelect(row) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="选择">
          <template v-slot="{ row, $index }">
            <el-link type="primary" :underline="false" @click="toSelectUser(row, $index)">选择用户</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 16px; width: 100%; text-align: center">
        <el-button type="primary" style="width: 60%" @click="toContinue">继续导入</el-button>
      </div>
      <el-dialog title="选择用户" :visible.sync="innerDialog" append-to-body :destroy-on-close="true">
        <account v-model="nameList" @select="selectUser"></account>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import filterBar from './filter_bar.vue';
import account from './account.vue';
const _ = require('lodash');
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: disclosure } = createNamespacedHelpers('disclosure');
const { mapActions: patent } = createNamespacedHelpers('patent');
export default {
  name: 'index',
  props: {},
  components: { account, filterBar },
  data: function () {
    return {
      filter: {},
      list: [],
      total: 0,
      fields: [
        { label: '申请号', model: 'create_number' },
        { label: '申请日', model: 'create_date' },
        { label: '标题', model: 'name' },
        { label: '发明人', model: 'inventor' },
        { label: '专利类型', model: 'type' },
      ],
      opera: [{ label: '查看', method: 'view' }],
      dialog: false,
      //错误
      errcode: undefined,
      temp_id: undefined,
      errorList: [],
      //选人
      innerDialog: false,
      nameList: [],
      listIndex: undefined,
    };
  },
  created() {
    this.search();
  },
  methods: {
    ...disclosure(['import', 'cacheImport', 'toExport']),
    ...patent(['query']),
    async search({ skip = 0, limit = 10 } = {}) {
      const info = _.cloneDeep(this.filter);
      const res = await this.query({ skip, limit, ...info, code: this.user.code });
      if (this.$checkRes(res)) {
        this.$set(this, `list`, res.data);
        this.$set(this, `total`, res.total);
      }
    },
    toView({ data }) {
      // TODO查看
    },
    // 导入
    async toImport(uri) {
      const res = await this.import({ uri });
      const { data } = res;
      if (data) {
        this.$message.error('导入失败');
        const { data: errorList, errcode, temp_id } = data;
        this.$set(this, 'errorList', errorList);
        this.$set(this, 'errcode', errcode);
        this.$set(this, 'temp_id', temp_id);
        this.dialog = true;
      } else {
        this.$set(this, 'errorList', []);
        this.$set(this, 'errcode', undefined);
        this.$set(this, 'temp_id', undefined);
        this.$message.success('导入成功');
      }
    },
    // 上传成功
    uSuccess(response, file, fileList) {
      const { uri } = response;
      this.$checkRes(response, '上传成功!正在导入,请稍后...');
      this.toImport(uri);
    },
    // 上传失败
    uError(err, file, fileList) {
      this.$message.error('上传失败');
    },
    // 正在上传
    uBefore() {
      this.$message('正在上传');
    },
    // 去选择用户
    toSelectUser(data, index) {
      this.$set(this, `nameList`, data.nameList);
      this.$set(this, `listIndex`, index);
      this.innerDialog = true;
    },
    // 选择用户
    selectUser(index) {
      let list = _.cloneDeep(this.nameList);
      list = list.map((i) => {
        i.is_select = false;
        return i;
      });
      list[index].is_select = true;
      this.$set(this.errorList[this.listIndex], 'nameList', list);
      this.innerDialog = false;
    },
    // 检查是否选择用户
    checkSelect(row) {
      const r = row.nameList.find((f) => f.is_select);
      return r ? '已选择' : '未选择';
    },
    // 继续导入
    async toContinue() {
      const r = this.errorList.find((f) => !f.nameList.find((f) => f.is_select));
      if (r) {
        this.$message.error('有未选择用户的数据,请重新检查');
        return;
      }
      const obj = { data: _.cloneDeep(this.errorList), temp_id: this.temp_id };
      const res = await this.cacheImport(obj);
      if (this.$checkRes(res, '操作成功', res.errmsg || '操作失败')) {
        this.dialog = false;
      }
    },
    async exportView() {
      const res = await this.toExport({ ...this.filter, code: this.user.code, id: this.user._id });
      if (this.$checkRes(res, '正在导出,请稍后')) {
      }
    },
    // 查看导出结果
    async toResult() {
      this.$router.push({ path: '/jg/patent/result' });
    },
    // 下载模板
    getTemplate() {
      window.open('../../数据模板.xlsx');
    },
  },
  computed: {
    ...mapState(['user']),
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

<style lang="less" scoped></style>
