<template>
  <div>

    <div>
      <div ref="lxHeader">
        <lx-header icon="md-apps" :text="is_search?$route.meta.title+'--'+select.keyword:$route.meta.title"
          style="margin-bottom: 10px; border: 0px; margin-top: 15px">
          <div slot="content" v-if="!hasMenu">
            <div class="searchwrap" style="display: flex;align-items: center;">
              <div>
                <el-input style="width:200px" v-model="select.title" placeholder="请输入名称"></el-input>
              </div>
              <div>
                <el-select style="width:200px" v-model="select.status" placeholder="请选择状态" clearable>
                  <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div v-if="is_search">
                <el-select style="width:200px" clearable @clear="clearCatalog" v-model="select.catalog_name"
                  placeholder="请选择目录">
                  <el-option value="">
                    <el-tree @node-click="getSelectedNodes" :data="catalogList" node-key="id" ref="tree"
                      highlight-current :props="defaultProps">
                    </el-tree>
                  </el-option>

                </el-select>
              </div>
              <div>
                <el-select style="width:200px" v-model="select.area_id" clearable multiple collapse-tags
                  placeholder="请选择区域">
                  <el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </div>

              <div>
                <el-select style="width:200px" v-model="select.tag_id" multiple collapse-tags placeholder="请选择标签">
                  <el-option v-for="item in tagList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div>
                <el-date-picker popper-class="pickerTime" :picker-options="pickerOptions" style="width:250px"
                  @change="changeStart" v-model="select.startRange" type="daterange" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="">
                </el-date-picker>
              </div>
              <div>
                <el-date-picker popper-class="pickerTime" :picker-options="pickerOptions" style="width:250px"
                  @change="changeEnd" v-model="select.endRange" type="daterange" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" range-separator="至" start-placeholder="结束日期" end-placeholder="">
                </el-date-picker>
              </div>
              <!-- <div>
                <el-select style="width:200px" v-model="select.records_status" placeholder="请选择是否到期">
                  <el-option v-for="item in rsList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </div> -->
              <div>
                <el-button type="primary" size="small" @click="select.page=1,getList()">查询</el-button>
              </div>
              <div>
                <el-button type="primary" size="small" @click="resetSearch">重置</el-button>
              </div>
              <div>
                <el-button type="primary" size="small" v-if="!is_search" @click="editIndex('add')">新增</el-button>
              </div>
              <div>
                <el-button type="primary" size="small" v-if="!hasMenu && !is_search" @click="goBack()">返回上一级</el-button>
              </div>
            </div>
          </div>

        </lx-header>
      </div>
    </div>

    <div class="catalog">
      <!-- <div class="catalog_left" :style="{'height': myHeight+'px',overflow:'scroll'}">
        <el-tree @node-click="getSelectedNodes" :data="catalogList" default-expand-all node-key="id" ref="tree"
          highlight-current :props="defaultProps">
        </el-tree>
      </div> -->
      <div v-if="hasMenu" class="catalog_list">
        <div v-for="item in showData" class='catalog_item' @click="clickIn(item)">
          <div>
            <div class="catalog_count" v-if="!(item.children&&item.children.length>0)">{{item.records_total}}</div>
            <div class="catalog_count" v-else>{{item.sub_records_total}}</div>
            <i :class="item.children&&item.children.length>0?'el-icon-folder-opened':'el-icon-document-copy'"></i>
            <div>{{item.name}}</div>
          </div>
        </div>
        <div @click="clickOut" class="catalog_item">
          <i v-if="historyList.length>0" class="el-icon-arrow-left"></i>
          <div>{{historyList.length>0?"返回上一级":""}}</div>
        </div>
      </div>

      <div class="catalog_right" v-else>
        <xy-table @getHeight="initHeight" @cell-dblclick="dbclick"	 :defaultExpandAll='false' :isPage="false" rowKey="id" :list="list"
          :table-item="table_item">
          <template v-slot:catalog_name>
            <el-table-column align='center' label="所属目录" width="240" header-align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.catalog_id_details && scope.row.catalog_id_details.length>0">
                  <el-tag style="margin-right:5px;margin-bottom:5px" v-for="item in scope.row.catalog_id_details">
                    {{item.name}}</el-tag>
                </div>
              </template>
            </el-table-column>
          </template>
          <template v-slot:area_name>
            <el-table-column align='center' label="所属区域" width="240" header-align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.area_ids_details && scope.row.area_ids_details.length>0">
                  <el-tag style="margin-right:5px;margin-bottom:5px" v-for="item in scope.row.area_ids_details">
                    {{item.name}}</el-tag>
                </div>
              </template>
            </el-table-column>
          </template>
          <template v-slot:tag_name>
            <el-table-column align='center' label="标签" width="240" header-align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.tag_ids_details && scope.row.tag_ids_details.length>0">
                  <el-tag style="margin-right:5px;margin-bottom:5px" v-for="item in scope.row.tag_ids_details">
                    {{item.name}}</el-tag>
                </div>
              </template>
            </el-table-column>
          </template>
          <template v-slot:status>
            <el-table-column align='center' label="状态" width="120" header-align="center">
              <template slot-scope="scope">
                <div v-for="item in statusList">
                  <el-tag :type="item.type" v-if="item.id===scope.row.status">
                    {{item.name}}</el-tag>
                </div>
              </template>
            </el-table-column>
          </template>
          <!-- <template v-slot:link_id>
            <el-table-column align='center' label="前续文档" width="120" header-align="center">
              <template slot-scope="scope">
                <div style="color:#b3241d;cursor: pointer;text-decoration: underline;" v-if="scope.row.link_id"
                  @click="showIndex('show',scope.row.link_id)">
                  查看
                </div>
              </template>
            </el-table-column>
          </template>
          <template v-slot:next_link_id>
            <el-table-column align='center' label="延续文档" width="120" header-align="center">
              <template slot-scope="scope">
                <div style="color:#b3241d;cursor: pointer;text-decoration: underline;" v-if="scope.row.next_link_id"
                  @click="showIndex('show',scope.row.next_link_id)">
                  查看
                </div>
              </template>
            </el-table-column>
          </template> -->

          <template v-slot:btns>
            <el-table-column align='center' fixed="right" label="操作" width="240" header-align="center">
              <template slot-scope="scope">
                <!-- <el-button type="primary" size="small" @click="editIndex('child',scope.row.id,scope.row.name)">子目录</el-button> -->
                <el-button type="primary" size="small" @click="showIndex('show',scope.row.id)">查看</el-button>
                <!--  -->
                <el-button v-if="stateObj.login_id===scope.row.admin_id || stateObj.is_admin" type="primary"
                  size="small" @click="editIndex('editor',scope.row.id,is_search)">编辑</el-button>
                <el-popconfirm v-if="stateObj.login_id===scope.row.admin_id || stateObj.is_admin" style="margin:0 10px"
                  @confirm="deleteList(scope.row.id)" title="确定删除吗？">
                  <el-button type="danger" size="small" slot="reference">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </template>
        </xy-table>
      </div>

    </div>

    <add-record ref="addRecord" @refresh="getList"></add-record>
    <show-record ref="showRecord"></show-record>
  </div>
</template>

<script>
  import addRecord from './components/addRecord.vue';
  import showRecord from './components/showRecord.vue';
  import {
    index,
    destroy
  } from "@/api/system/baseForm.js"
  import {
    catalogTotal
  } from "@/api/home/index.js"

  import state from '@/store/modules/user.js'
  export default {
    components: {
      addRecord,
      showRecord
    },
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近半年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '本年度',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              const currentYear = new Date().getFullYear();
              const firstDayOfYear = new Date(currentYear, 0, 1);
              const lastDayOfYear = new Date(currentYear, 11, 31);
              start.setTime(firstDayOfYear);
              end.setTime(lastDayOfYear)
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '本月度',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              const currentYear = start.getFullYear();
              const month = start.getMonth() + 1;
              const firstDayOfMonth = new Date(currentYear, start.getMonth(), 1);
              const lastDayOfMonth = new Date(currentYear, month, 0);
              start.setTime(firstDayOfMonth);
              end.setTime(lastDayOfMonth);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '本周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              const date = new Date();
              const today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
              const firstDay = new Date(today);
              const lastDay = new Date(today);
              const diff = 1 - today.getDay();
              firstDay.setDate(today.getDate() + diff); // 获取本周第一天的日期
              lastDay.setDate(today.getDate() + (6 - today.getDay() + 1)); // 获取本周最后一天的日期
              start.setTime(firstDay);
              end.setTime(lastDay);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        rsList: [{
          id: 1,
          name: '是'
        }, {
          id: 0,
          name: '否'
        }],
        select: {
          title: '',
          keyword:'',
          table_name: 'records',
          page: 1,
          page_size: 9999,
          catalog_id: '',
          catalog_name: '',
          status: '',
          area_id: '',
          tag_id: '',
          startRange: [],
          endRange: [],
          // records_status:''
        },
        hasMenu: false,
        myHeight: 0,
        stateObj: {},
        total: 0,
        list: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        catalogList: [],
        historyList: [],
        menuName: [],
        showData: [],
        catalogChildren: [], // 存储所有数据
        areaList: [],
        tagList: [],
        nowDate: '',
        is_search: false,

        statusList: [{
          id: 0,
          name: '正常',
          type: ''
        }, {
          id: 3,
          name: '已结束',
          type: 'info'
        }, {
          id: 1,
          name: '已到期',
          type: 'warning'
        }, {
          id: 2,
          name: '已延续',
          type: 'success'
        }],
        table_item: [{
            type: 'index',
            width: 50,
            fixed: 'left'
          }, {
            prop: 'title',
            label: '标题',
            align: 'left',
            width: 360,
            headerAlign: 'center'
          },
          {
            prop: 'date',
            label: '开始日期',
            align: 'center',
            width: 120
          },
          {
            prop: 'end_date',
            label: '结束日期',
            align: 'center',
            width: 120
          },
          {
            prop: 'tag_name',
            label: '标签',
            align: 'center',
            width: 240
          },
          {
            prop: 'area_name',
            label: '所属区域',
            align: 'center',
            width: 240
          },
          {
            prop: 'status',
            label: '状态',
            align: 'center',
            width: 120
          },
          {
            prop: 'catalog_name',
            label: '所属目录',
            align: 'center',
            width: 240
          },
          // {
          //   prop: 'link_id',
          //   label: '来源文档',
          //   align: 'center',
          //   width: 120
          // },
          // {
          //   prop: 'next_link_id',
          //   label: '延续文档',
          //   align: 'center',
          //   width: 120
          // },

        ]

      }
    },
    created() {
      //
      this.nowDate = this.$moment().add(1, 'months').format('YYYY-MM-DD')
      this.startDate = this.$moment('1900-01-01').format("YYYY-MM-DD")
      this.stateObj = state.state
      this.is_search = false
      if (this.$route.query.searchTitle) {
        this.select.keyword = this.$route.query.searchTitle
        this.getCatalogList()
        this.is_search = true
      }
      if (this.$route.query.dateTotal) {
        this.select.endRange = [this.startDate, this.nowDate]
        this.select.status = 0
        this.is_search = true
      }
      if (this.$route.query.status1Total) {
        this.select.status = 1
        this.is_search = true
      }
      // this.getCatalogList()
      // 分辨是有下级的 还是直接显示列表
      if (this.$route.path) {
        let path = this.$route.path.split("_")
        this.select.catalog_id = path[1]
        if (this.$route.path.includes('menu')) {
          this.hasMenu = true
          this.getCatalogList(path[1])
        } else {
          this.getCatalogList()
          this.getList()
        }
        this.getAreaList()
        this.getTagList()
      }
    },
    watch: {
      '$route'(to, from) {
        this.$router.go(0);
      }
    },
    methods: {
      initHeight(e) {
        console.log("e", e)
        this.myHeight = e + 37
      },
      getSelectedNodes(data, node) {
        console.log("data", data, node)
        if (data.children && data.children.length > 0) {
          // node.disabled = true
          return
        }
        // this.$refs.tree.setCheckedKeys([]); // 删除所有选中节点
        // this.$refs.tree.setCheckedNodes([data]); // 选中已选中节点
        this.select.catalog_id = data.id
        this.select.catalog_name = data.name
        this.$refs.tree.setCurrentKey(data.id)
        this.$forceUpdate()
      },
      clearCatalog(e) {
        this.select.catalog_id = ''
        this.select.catalog_name = ''

        this.$refs.tree.setCurrentKey(null)
      },
      toUrl(item) {
        let path = ''
        if (item.children && item.children.length > 0) {
          // path = '/record/menu_' + item.id + '?time=' + new Date()
          this.catalogChildren = item.children
        } else {
          path = '/record/index_' + item.id
          this.$router.push({
            path: path
          })
        }

      },
      clickIn(i) {
        if (i.children && i.children.length > 0) {
          this.historyList.push(this.showData);
          this.showData = i.children;
          this.menuName.push(i.name)
          this.select.catalog_name = ' / ' + this.menuName.join(" / ")
          console.log(this.historyList);
          let totalId = []
          this.showData.map(item=>{
            totalId.push(item.id)
          })
          this.getCatalogTotal(totalId.join(','))
        } else {
          this.select.catalog_id = i.id
          this.menuName.push(i.name)
          this.select.catalog_name = ' / ' + this.menuName.join(" / ")
          this.hasMenu = false
          this.getList()
        }
      },
      clickOut() {
        if (this.historyList && this.historyList.length > 0) {
          this.showData = this.historyList[this.historyList.length - 1]
          this.menuName.splice(this.menuName.length - 1, 1)
          this.select.catalog_name = ' / ' + this.menuName.join(" / ")
          this.historyList.pop()
          console.log(this.historyList);
        }
      },
      goBack() {
        this.select.catalog_id = ''
        this.menuName.splice(this.menuName.length - 1, 1)
        this.select.catalog_name = ' / ' + this.menuName.join(" / ")
        this.hasMenu = true
      },

      async getCatalogList(pid) {
        const res = await index({
          page_size: 999,
          page: 1,
          sort_type: 'ASC',
          sort_name: 'sort',
          table_name: 'catalogs',
          // is_auth: 1,
        })
        if (res.data.length > 0) {
          this.catalogList = this.base.buildTree(res.data)
          if (pid) {
            let pList = this.base.findNodesById(this.catalogList, pid)
            console.log("pList", pList)
            this.catalogChildren = pList[0].children
            this.showData = this.catalogChildren
            let totalId = []
            this.showData.map(item=>{
              totalId.push(item.id)
            })
            this.getCatalogTotal(totalId.join(','))
          }
        }
      },
      async getCatalogTotal(ids){
        const res = await catalogTotal({
          ids:ids
        })
        let data = res.list
        const updatedB = this.showData.map((item) => {
          // 在数组 a 中查找匹配的 id
          const matchedItem = data.find((aItem) => aItem.id == item.id);

          // 如果找到匹配项，则将 records_total 和 sub_records_total 添加到当前项
          if (matchedItem) {
            return {
              ...item,
              records_total: matchedItem.records_total,
              sub_records_total: matchedItem.sub_records_total
            };
          }else{
            return {
              ...item,
              records_total: 0,
              sub_records_total: 0
            };
          }

          // 如果没有找到匹配项，则返回原项
          return item;
        });
        this.showData = updatedB
        console.log("this.showData",this.showData)
      },
      async getAreaList() {
        const res = await index({
          page_size: 999,
          page: 1,
          sort_type: 'ASC',
          sort_name: 'sort',
          table_name: 'areas',
        })
        this.areaList = res.data

      },
      async getTagList() {
        const res = await index({
          page_size: 999,
          page: 1,
          sort_type: 'ASC',
          sort_name: 'sort',
          table_name: 'record_tags',
          is_auth: 1
        })
        this.tagList = res.data

      },

      dbclick(row, column, cell, event){
        console.log("row",row)
        this.showIndex("show",row.row.id)
      },
      editIndex(type, id,is_search) {
        if(is_search){
          this.$refs.addRecord.is_search = true
        }
        if (type == 'editor') {
          this.$refs.addRecord.id = id
        } else {
          this.$refs.addRecord.setCheck(this.select.catalog_id)
        }
        // if(this.select.catalog_id){
        //   this.$refs.addRecord.setCatalogId(this.select.catalog_id)
        // }
        this.$refs.addRecord.setList(this.catalogList, this.areaList, this.tagList)
        this.$refs.addRecord.type = type
        this.$refs.addRecord.isShow = true
      },
      showIndex(type, id) {
        this.$refs.showRecord.id = id
        this.$refs.showRecord.type = type
        this.$refs.showRecord.isShow = true
      },
      resetSearch() {
        this.select.page = 1
        this.select.keyword = ''
        this.select.area_id = []
        this.select.tag_id = []
        this.select.startRange = []
        this.select.endRange = []
        // this.select.records_status = ""
        if (this.is_search) {
          this.select.catalog_id = ''
          this.select.catalog_name = ''
          this.$refs.tree.setCurrentKey(null)
        } else {
          this.select.title = ''
        }
        // this.select.catalog_id = ''
        this.getList()
      },
      changeStart(e) {
        if (e) {
          this.select.startRange = e
        } else {
          this.select.startRange = []
        }
      },
      changeEnd(e) {
        if (e) {
          this.select.endRange = e
        } else {
          this.select.endRange = ''
        }
      },
      async getList() {
        const res = await index({
          page_size: this.select.page_size,
          page: this.select.page,
          table_name: this.select.table_name,
          json_data_fields: ['files', 'area_ids', 'tag_ids', 'catalog_id'],
          is_auth: 1,
          sort_type: 'DESC',
          sort_name: 'date',
          catalogs_id: this.select.catalog_id ? this.select.catalog_id : '',
          area_ids: this.select.area_id ? this.select.area_id : '',
          tag_ids: this.select.tag_id ? this.select.tag_id : '',
          keyword:this.select.keyword?this.select.keyword:'',
          // records_status:this.select.records_status,
          filter: [{
            "key": "title",
            "op": "like",
            "value": this.select.title
          }, {
            key: 'date',
            op: 'range',
            value: this.select.startRange ? this.select.startRange : []
          }, {
            key: 'end_date',
            op: 'range',
            value: this.select.endRange ? this.select.endRange : []
          }, {
            key: 'status',
            op: 'eq',
            value: this.select.status
          }]
        })
        // this.list = res.data
        if (res.data.length > 0) {
          this.list = this.base.buildTree(res.data, 'link_id')
        } else {
          this.list = []
        }
      },
      deleteList(id) {
        var that = this;
        destroy({
          id: id,
          table_name: this.select.table_name
        }).then(response => {
          this.$Message.success('操作成功');
          this.getList()
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .searchwrap {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    &>div {
      display: flex;
      align-items: center;
      margin-right: 10px;
      margin-bottom: 10px;

      span {
        min-width: 70px;
      }
    }
  }

  .catalog {
    &_list {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
    }

    &_item {
      // width:150px;
      text-align: center;
      font-size: 18px;
      margin: 20px;
      cursor: pointer;
      color: #b3241d;
      width: 150px;
      height: 130px;
      position: relative;

      i {
        font-size: 40px;
        margin-bottom: 10px;
      }
    }

    &_count {
      position: absolute;
      top: 0;
      right: 0;
      padding: 0px 10px;
      background: #b3241d;
      border-radius: 10px;
      color: #fff;
      font-size: 12px;
    }
  }

  ::v-deep .el-checkbox__input .el-checkbox__inner {
    border-radius: 50%;
  }
</style>
