<template>
  <el-container class="patent-setting">
    <el-header>
      <div style="margin-left: 15px;">
        <el-button type="success" size="small" icon="el-icon-check" @click="handleCheck(1)">列表全选</el-button>
        <el-button type="danger" size="small" icon="el-icon-minus" @click="handleCheck(0)">全部取消</el-button>
      </div>
      <div style="float: right;margin-right: 25px;">
        <el-popover
            placement="bottom"
            title=""
            width="300"
            trigger="click"
        >
          <div style="height: 400px;overflow-y: auto">
            <div v-for="item in reportList" style="margin-bottom: 10px;line-height: 30px;background: #e4e4e4;padding: 5px;margin-right: 5px;border-radius: 5px;">
              <div>
                <span>报告名称：{{ item.name }}</span>
              </div>
              <div>
                <span>创建时间：{{ item.createTime }}</span>
              </div>
              <div>
                <span>下载文件：</span>
                <el-link type="primary" v-if="item.status === 1" @click.native="handleDownload(item)">点击下载</el-link>
                <span v-else-if="item.status === 0">等待文件生成</span>
                <span v-else style="color: red">生成失败</span>
              </div>
            </div>
          </div>
          <el-button type="primary" size="small" slot="reference">
            <span>生成记录</span>
            <span style="padding-left: 5px;">({{ reportList.length }})</span>
          </el-button>
        </el-popover>
      </div>
    </el-header>
    <el-main style="background: #fff" v-if="showList">
      <el-table :data="dataList" border header-row-class-name="custom-table-header">
        <el-table-column prop="" label="" width="55" align="center">
          <template slot-scope="scope">
            <el-checkbox :checked="getValueIndex(scope.row.id) !== -1" @change="handleClick(scope.row)"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column prop="patentno" label="专利号" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="applicationno" label="申请号" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="name" label="专利名称" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column label="申请人" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <div v-for="(name, index) in scope.row.applicant">{{ name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="权利人" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <div v-for="(name, index) in scope.row.obligee">{{ name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="专利类型" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <table-tag style="display: inline-block" :dict-data="$constants.patentType" :value="scope.row.type" effect="dark" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="法律状态" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <table-tag style="display: inline-block" :dict-data="$constants.patentSimpleStatus" :value="scope.row.status" effect="dark" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="标签" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <div v-for="(label, index) in scope.row.label">
              <span class="tag" :style="{ background: colorList[index % 10] }">{{ label }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div @click="drawer = true" class="search-option">
        <i class="el-icon-d-arrow-left" style="font-size: 20px;"></i>
      </div>
    </el-main>

    <el-drawer :withHeader="false" :visible.sync="drawer" size="350px" direction="rtl" :before-close="beforeClose">
      <el-container>
        <el-header class="search-tabs">
          <el-tabs v-model="activeName" type="card">
            <el-tab-pane label="专利信息" name="1"></el-tab-pane>
            <el-tab-pane label="自定义字段" name="2"></el-tab-pane>
          </el-tabs>
        </el-header>
        <el-main style="padding: 0;">
          <el-collapse v-model="activeNames" v-if="activeName === '1'">
            <el-collapse-item title="申请人" name="1">
              <el-container>
                <el-main style="max-height: 200px;">
                  <el-checkbox-group v-model="queryParams.applicant">
                    <el-row v-for="item in searchData.applicant">
                      <el-checkbox :label="item.name"></el-checkbox>
                    </el-row>
                  </el-checkbox-group>
                </el-main>
              </el-container>
            </el-collapse-item>
            <el-collapse-item title="权利人" name="2">
              <el-container>
                <el-main style="max-height: 200px;">
                  <el-checkbox-group v-model="queryParams.obligee">
                    <el-row v-for="item in searchData.obligee">
                      <el-checkbox :label="item.name"></el-checkbox>
                    </el-row>
                  </el-checkbox-group>
                </el-main>
              </el-container>
            </el-collapse-item>
            <el-collapse-item title="法律状态" name="3">
              <el-container>
                <el-main style="max-height: 200px;">
                  <el-checkbox-group v-model="queryParams.status">
                    <el-row v-for="item in $constants.patentSimpleStatus">
                      <el-checkbox :label="item.value" v-if="patentList.map(patent => patent.status).indexOf(item.value) !== -1">{{ item.label }}</el-checkbox>
                    </el-row>
                  </el-checkbox-group>
                </el-main>
              </el-container>
            </el-collapse-item>
            <el-collapse-item title="专利类型" name="4">
              <el-container>
                <el-main style="max-height: 200px;">
                  <el-checkbox-group v-model="queryParams.type">
                    <el-row v-for="item in $constants.patentType">
                      <el-checkbox :label="item.value" v-if="patentList.map(patent => patent.type).indexOf(item.value) !== -1">{{ item.label }}</el-checkbox>
                    </el-row>
                  </el-checkbox-group>
                </el-main>
              </el-container>
            </el-collapse-item>
          </el-collapse>

          <el-collapse v-model="activeNames2" v-if="activeName === '2'">
            <el-collapse-item title="标签" name="1">
              <el-container>
                <el-main style="max-height: 200px;">
                  <el-checkbox-group v-model="queryParams2.label">
                    <el-row v-for="item in searchData2.label">
                      <el-checkbox :label="item"></el-checkbox>
                    </el-row>
                  </el-checkbox-group>
                </el-main>
              </el-container>
            </el-collapse-item>
            <el-collapse-item title="文件夹" name="2">
              <el-container>
                <el-main style="max-height: 400px;">
                  <el-tree
                      ref="folder"
                      :default-checked-keys="queryParams2.folder"
                      :data="searchData2.field.folder"
                      :props="defaultProps"
                      show-checkbox
                      node-key="id"
                      check-strictly
                      @check-change="handleCheckChange('folder')"
                  ></el-tree>
                </el-main>
              </el-container>
            </el-collapse-item>
            <el-collapse-item title="标引" name="3">
              <el-container>
                <el-main style="max-height: 500px;">
                  <template v-for="(item, index) in searchData2.field.index">
                    <p class="field-title">{{ item.name }}</p>
                    <template v-if="item.type === 3 || item.type === 4 || item.type === 5">
                      <el-checkbox-group v-model="queryParams2.field[item.id]">
                        <el-row v-for="option in item.option">
                          <el-checkbox :label="option.id">{{ option.name }}</el-checkbox>
                        </el-row>
                      </el-checkbox-group>
                    </template>
                    <template v-if="item.type === 1">
                      <el-date-picker v-model="queryParams2.field[item.id]" type="date" size="small" placeholder="选择日期" style="width: 100%;"></el-date-picker>
                    </template>
                    <template v-if="item.type === 2">
                      <el-input v-model="queryParams2.field[item.id]" placeholder="请输入内容" size="small"></el-input>
                    </template>
                  </template>
                </el-main>
              </el-container>
            </el-collapse-item>
            <el-collapse-item title="分类" name="4">
              <el-container>
                <el-main style="max-height: 500px;">
                  <template v-for="(item, index) in searchData2.field.classify">
                    <p class="field-title">{{ item.name }}</p>
                    <el-tree
                        :ref="item.id"
                        :default-checked-keys="queryParams2.field[item.id]"
                        :data="item.option"
                        :props="defaultProps"
                        show-checkbox
                        node-key="id"
                        check-strictly
                        @check-change="handleCheckChange(item.id)"
                    ></el-tree>
                  </template>
                </el-main>
              </el-container>
            </el-collapse-item>
          </el-collapse>
        </el-main>
        <el-footer style="text-align: right;height: 70px;">
          <el-button @click="resetSearchQuery">重置</el-button>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-footer>
      </el-container>
    </el-drawer>

    <el-footer style="height: 70px;text-align: right">
      <el-button>关 闭</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </el-footer>
  </el-container>
</template>

<script>
import { downLoad2, formatDate, getFileName } from "@/utils";
import TableTag from "@/components/TableTag";
import { mapGetters } from "vuex";
export default {
  components: { TableTag },
  data() {
    return {
      activeNames: [],
      activeNames2: [],
      activeName: '1',
      showList: true,
      refresh: true,
      dataList: [],
      queryParams: {},
      queryParams2: {},
      drawer: false,
      reportList: [],
      searchData: {
        applicant: [],
        status: [],
        obligee: [],
        type: []
      },
      colorList: [
        '#409eff',
        '#67c23a',
        '#909399',
        '#f56c6c',
        '#e6a23c',
        '#e63c91',
        '#e6553c',
        '#3ce6cc',
        '#8e3ce6',
        '#e63c3c'
      ],
      searchData2: {
        field: {},
        label: []
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed: {
    ...mapGetters(['patentField', 'customField']),
    template() {
      return this.$store.state.report.template
    },
    patentList() {
      return this.$store.state.report.patentList
    },
    form() {
      return this.$store.state.report.form
    },
    activeItem() {
      return this.$store.state.report.activeItem
    },
    patentKey() {
      return this.$store.state.chart.patentKey
    }
  },
  mounted() {
    this.getReportList()
    if (this.template.label.length) {
      this.resetSearchQuery()
      for (let key in this.searchData) {
        this.getSearchData(key)
      }
      for (let key in this.searchData2) {
        this.getSearchData2(key)
      }
    }
  },
  methods: {
    getReportList() {
      this.$api.getReportList({ patentKey: this.patentKey }).then(response => {
        this.reportList = response.data
      })
    },
    handleConfirm() {
      this.$emit('submit', {})
    },
    handleCheckChange(id) {
      if (id === 'folder') {
        const data = this.$refs[id].getCheckedNodes()
        this.queryParams2.folder = data.map(item => item.id)
      } else {
        const data = this.$refs[id][0].getCheckedNodes()
        this.$set(this.queryParams2.field, id, data.map(item => item.id))
      }
    },
    getSearchData2(key) {
      switch (key) {
        case 'label':
          let value = [];
          this.dataList.map(item => {
            item.label.map(v => {
              value.push(v)
            })
          })
          this.$set(this.searchData2, key, [...new Set(value)])
          break
        case 'field':
          let data = {};
          for (let field in this.customField) {
            switch (field) {
              case 'folder':
                data[field] = this.customField[field];
                break
              case 'classify':
              case 'index':
                let ids = new Set();
                let arr = []
                this.dataList.map(item => item.field.map(f => {
                  ids.add(f.id)
                }));
                this.customField[field].map(item => {
                  if ([...ids].indexOf(item.id) !== -1) {
                    arr.push(item)
                  }
                });
                data[field] = arr
                break
            }
          }
          this.resetIndexFieldId()
          this.$set(this.searchData2, key, data)
          break
      }
    },
    resetIndexFieldId() {
      this.customField.index.map(item => {
        if (item.type === 1 || item.type === 2) {
          this.$set(this.queryParams2.field, item.id, null)
        } else {
          this.$set(this.queryParams2.field, item.id, [])
        }
      })
    },
    handleSelect(index, indexPath) {
      this.activeItem = index
    },
    beforeClose() {
      this.drawer = false
    },
    resetSearchQuery() {
      this.queryParams = {
        applicant: [],
        status: [],
        name: "",
        no: "",
        obligee: [],
        type: [],
      }
      this.queryParams2 = {
        field: {},
        label: [],
        folder: []
      }
      this.resetIndexFieldId()
      this.activeNames = []
      this.activeNames2 = []
      this.activeName = '1'
      this.dataList = JSON.parse(JSON.stringify(this.patentList))
      this.drawer = false
      this.refreshTableList()
    },
    handleSearch() {
      let dataList = JSON.parse(JSON.stringify(this.patentList))
      for (let key in this.queryParams) {
        if (this.queryParams[key].length) {
          if (key === 'applicant' || key === 'obligee') {
            dataList = dataList.map(item => {
              for (let value of item[key]) {
                if (this.queryParams[key].indexOf(value) !== -1) {
                  return item
                }
              }
            }).filter(item => item !== undefined)
          } else {
            dataList = dataList.filter(item => this.queryParams[key].indexOf(item[key]) !== -1)
          }
        }
      }
      if (this.queryParams2.label.length) {
        dataList = dataList.map(item => {
          for (let label of item.label) {
            if (this.queryParams2.label.indexOf(label) !== -1) {
              return item
            }
          }
        }).filter(item => item !== undefined)
      }
      if (this.queryParams2.folder.length) {
        dataList = dataList.map(item => {
          for (let folder of item.folder) {
            if (this.queryParams2.folder.indexOf(folder) !== -1) {
              return item
            }
          }
        }).filter(item => item !== undefined)
      }
      for (let key in this.queryParams2.field) {
        if (!this.queryParams2.field[key] || (this.queryParams2.field[key] instanceof Array && this.queryParams2.field[key].length === 0)) {
          continue
        }
        const index = this.searchData2.field.index.find(index => index.id === parseInt(key))
        const classify = this.searchData2.field.classify.find(index => index.id === parseInt(key))
        dataList = dataList.map(item => {
          for (let field of item.field) {
            if (field.id === parseInt(key)) {
              if (index) {
                switch (index.type) {
                  case 0:
                  case 1:
                  case 2:
                    let data
                    if (index.type === 1) {
                      data = formatDate(this.queryParams2.field[key]);
                    } else {
                      data = this.queryParams2.field[key]
                    }
                    if (data == field.value) {
                      return item
                    }
                    break
                  case 3:
                  case 4:
                    if (this.queryParams2.field[key].indexOf(field.value) !== -1) {
                      return item
                    }
                    break
                  case 5:
                    for (let value of field.value) {
                      if (this.queryParams2.field[key].indexOf(value) !== -1) {
                        return item
                      }
                    }
                    break
                }
              } else if (classify) {
                for (let value of field.value) {
                  if (this.queryParams2.field[key].indexOf(value) !== -1) {
                    return item
                  }
                }
              }
            }
          }
        }).filter(item => item !== undefined)
      }
      // console.log(dataList)
      this.dataList = dataList
      this.drawer = false
      this.refreshTableList()
    },
    getSearchData(key) {
      let temp = []
      this.dataList.map(item => {
        if (item[key] instanceof Array) {
          item[key].map(c => temp.push(c))
        } else {
          temp.push(item[key])
        }
      })
      this.$set(this.searchData, key, [...new Set(temp)].map(item => {
        return {
          name: item,
          count: 0
        }
      }))
    },
    getLabelValue() {
      const label = this.form.patentList.find(item => item.label === parseInt(this.activeItem))
      if (label === undefined) {
        return false
      }
      return label
    },
    getValueIndex(id) {
      const label = this.getLabelValue()
      return label ? label.id.indexOf(id) : -1
    },
    handleDownload(item) {
      downLoad2(item.path)
    },
    handleCheck(type) {
      const ids = this.dataList.map(item => item.id)
      const label = parseInt(this.activeItem)
      let patentList = this.form.patentList.find(item => item.label === label)
      switch (type) {
        case 0:
          if (patentList) {
            ids.map(id => {
              const index = patentList.id.indexOf(id)
              if (index !== -1) {
                patentList.id.splice(index, 1)
              }
            })
          }
          break
        case 1:
          if (patentList) {
            ids.map(id => {
              if (patentList.id.indexOf(id) === -1) {
                patentList.id.push(id)
              }
            })
          } else {
            this.form.patentList.push({
              id: ids,
              label: label
            })
          }
          break
      }
      this.refreshTableList()
    },
    refreshTableList() {
      this.showList = false
      this.$nextTick(() => {
        this.showList = true
      })
    },
    handleClick(item) {
      let label = this.getLabelValue()
      if (!label) {
        this.form.patentList.push({
          id: [item.id],
          label: parseInt(this.activeItem)
        })
        return false
      }
      const index = this.getValueIndex(item.id)
      if (index !== -1) {
        label.id.splice(index, 1)
      } else {
        label.id.push(item.id)
      }
    }
  }
}
</script>

<style lang="less">
.patent-setting {
  .el-menu-item.is-active {
    outline: 0;
    background-color: #ecf5ff !important;
  }
  .el-collapse-item__header {
    padding: 0 20px !important;
  }
  .search-tabs {
    .el-tabs__header {
      margin-top: 35px !important;
    }
  }
  .el-collapse {
    border-top: 0 !important;
  }
  .field-title {
    font-weight: bold;
    margin: 0 !important;
    padding: 10px 0;
  }
  .title {
    .name {
      font-size: 17px;
      color: #409EFF;
    }
    .el-tag {
      margin-left: 10px;
    }
    .no {
      padding-left: 15px;
      color: #515a6e;
      font-size: 13px;
    }
  }
  .applicant, .obligee, .type, .label {
    margin-top: 10px;
    .title {
      width: 70px;
      float: left;
      font-weight: bold;
    }
    .name {
      overflow: hidden;
      span {
        padding-right: 5px;
      }
    }
  }
  .tag {
    display: inline-block;
    color: #fff;
    padding: 0px 5px;
    border-radius: 4px;
    margin-right: 5px;
    margin-top: 5px;
  }
}
</style>
