<template>
  <div class="table-page">
    <div class="table-page-content">
      <div class="left-tree">
        <tree-side
          ref="treeSide"
          :dataLoading="treeLoading"
          :default-expand-all="false"
          :defaultProps="defaultProps"
          :tabList="['行政维度']"
          :treeData="treeData"
          isDeselect
          @currentChange="currentChange"
        ></tree-side>
      </div>
      <div class="right-table">
        <div class="full-page bg">
          <div class="search-box">
            <div ref="btnPanel" class="btn-box">
              <el-button
                :disabled="multiSelectData.length === 0"
                :loading="downloadLoading"
                class="btn btn-plus"
                icon="el-icon-download"
                size="small"
                type="success"
                @click="exportData"
              >档案导出
              </el-button>
            </div>
            <div class="search-box-combination">
              <div class="search-box-label">任务时间：</div>
              <div>
                <el-date-picker
                  v-model="params.querys[5].value"
                  end-placeholder="任务时间（结束）"
                  range-separator="至"
                  start-placeholder="任务时间（开始）"
                  style="width: 280px"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  @change="datePickerChange"
                >
                </el-date-picker>
              </div>
              <SearchCommon :optionList="optionList" @search="handleSearch" />
            </div>
          </div>
          <div class="main-table-container">
            <div class="table-container" style="padding: 20px">
              <div ref="tableRef" class="table-content">
                <el-table
                  ref="multipleSelection"
                  v-loading="tableLoading"
                  :data="tableData"
                  :default-sort="getSorterDirection(params, true)"
                  :max-height="tableMaxHeight"
                  border
                  class="table-list"
                  element-loading-background="rgba(10 ,38 ,61, 0.9)"
                  row-key="id"
                  stripe
                  @select="handleSelection"
                  @selection-change="handleSelectionChange"
                  @sort-change="sortChange"
                >
                  <el-table-column align="center" type="selection" width="55" />
                  <el-table-column
                    :index="
                      index =>
                        index +
                        1 +
                        (params.pageBean.page - 1) * params.pageBean.pageSize
                    "
                    align="center"
                    label="序号"
                    type="index"
                    width="70"
                  />
                  <el-table-column
                    :formatter="({roadName}) => roadName || '-'"
                    align="center"
                    label="所属路段"
                    prop="roadCode"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({teamName}) => teamName || '-'"
                    align="center"
                    label="巡检队伍"
                    prop="teamName"
                    show-overflow-tooltip
                    width="120"
                  />
                  <el-table-column
                    :formatter="({startPatrolName}) => startPatrolName || '-'"
                    align="center"
                    label="开始巡检站"
                    prop="startPatrolName"
                    show-overflow-tooltip
                    width="120"
                  />
                  <el-table-column
                    :formatter="({endPatrolName}) => endPatrolName || '-'"
                    align="center"
                    label="结束巡检站"
                    prop="endPatrolName"
                    show-overflow-tooltip
                    width="120"
                  />
                  <!--                  <el-table-column-->
                  <!--                    :formatter="-->
                  <!--                      ({planType}) =>-->
                  <!--                        dictionaryEscape('xjlx-xjrw', planType) || '-'-->
                  <!--                    "-->
                  <!--                    align="center"-->
                  <!--                    label="巡检类型"-->
                  <!--                    prop="planType"-->
                  <!--                    show-overflow-tooltip-->
                  <!--                    sortable="custom"-->
                  <!--                    width="120"-->
                  <!--                  />-->
                  <el-table-column
                    :formatter="({inspectUsersName}) => inspectUsersName || '-'"
                    align="center"
                    label="巡检人"
                    prop="inspectUsersName"
                    show-overflow-tooltip
                    width="100"
                  />
                  <el-table-column
                    :formatter="({taskDate}) => taskDate || '-'"
                    align="center"
                    label="巡检时间"
                    prop="taskDate"
                    show-overflow-tooltip
                    sortable="custom"
                    width="120"
                  />
                  <el-table-column
                    :formatter="({startTime}) => startTime || '-'"
                    align="center"
                    label="巡检开始时间"
                    prop="startTime"
                    show-overflow-tooltip
                    sortable="custom"
                    width="140"
                  />
                  <el-table-column
                    :formatter="({endTime}) => endTime || '-'"
                    align="center"
                    label="巡检结束时间"
                    prop="endTime"
                    show-overflow-tooltip
                    sortable="custom"
                    width="140"
                  />
                  <el-table-column
                    align="center"
                    label="巡检状态"
                    prop="taskStatus"
                    show-overflow-tooltip
                    width="100"
                  >
                    <template v-slot="{row}">
                      <div :style="{color: statusStyle(row.taskStatus)}">
                        {{ dictionaryEscape('xc_zt', String(row.taskStatus)) }}
                      </div>
                    </template>
                  </el-table-column>
                  <!--                  <el-table-column-->
                  <!--                    :formatter="({taskDate}) => taskDate || '-'"-->
                  <!--                    align="center"-->
                  <!--                    label="任务时间"-->
                  <!--                    prop="taskDate"-->
                  <!--                    show-overflow-tooltip-->
                  <!--                    sortable-->
                  <!--                    width="120"-->
                  <!--                  />-->
                  <el-table-column
                    :formatter="({requestPoint}) => requestPoint != null ? requestPoint : '-'"
                    align="center"
                    label="应打卡点"
                    prop="requestPoint"
                    show-overflow-tooltip
                    width="80"
                  />
                  <el-table-column
                    :formatter="({reportingPoint}) => reportingPoint != null ? reportingPoint : '-'"
                    align="center"
                    label="上报点"
                    prop="reportingPoint"
                    show-overflow-tooltip
                    width="80"
                  />
                  <el-table-column
                    :formatter="({fixedPoint}) => fixedPoint != null ? fixedPoint : '-'"
                    align="center"
                    label="固定点"
                    prop="fixedPoint"
                    show-overflow-tooltip
                    width="80"
                  />
                  <el-table-column
                    :formatter="({tempPoint}) => tempPoint != null ? tempPoint : '-'"
                    align="center"
                    label="临时点"
                    prop="tempPoint"
                    show-overflow-tooltip
                    width="80"
                  />
                  <el-table-column
                    :formatter="({outlierPoint}) => outlierPoint != null ? outlierPoint : '-'"
                    align="center"
                    label="异常点"
                    prop="outlierPoint"
                    show-overflow-tooltip
                    width="80"
                  />
                  <el-table-column
                    align="center"
                    label="打卡状态"
                    prop="outlierPoint"
                    show-overflow-tooltip
                    width="100"
                  >
                    <template v-slot="{row}">
                      <div :style="{color: dakaStyle(row)}">
                        {{ row.taskStatus !== 4 ? '-' : (row.fixedPoint >= row.requestPoint ? '正常' : '异常') }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    fixed="right"
                    label="操作"
                    min-width="200"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <el-link
                        :underline="false"
                        type="primary"
                        @click="changePage('TablePage', row)"
                      >
                        点位查询
                      </el-link>
                      <el-link
                        :underline="false"
                        type="primary"
                        @click="filePreviewChange(row)"
                      >
                        预览
                      </el-link>
                    </template>
                  </el-table-column>
                </el-table>
                <pagination
                  ref="paginationPanel"
                  :pageResult="params.pageBean"
                  style="margin-top: 10px"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <FileDialog
      :file-info="fileInfo"
      :is-show.sync="fileShowDialog"
    />
  </div>
</template>

<script>
import {exportDataFile, tableYiChaData} from '@/api/patrolAndRescue/roadWatch/inspectionResults'
import pagination from '@/components/SuperPagination/index.vue'
import SearchCommon from '@/components/SearchCommon/index.vue'
import PubSub from 'pubsub-js'
import {TableMixin} from '@/mixins/tableMixin'
import {getSorterDirection, refineRequestBody, setQueryValue} from '@/utils/requestWrappers'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import treeSide from '@/components/treeSide/index.vue'
import moment from 'moment'
import FileDialog from '@/views/patrolAndRescue/roadWatch/AbnormalHandling/components/FileDialog/index.vue'
import {getTree} from '@/api/tree'

export default {
  name: 'TaskPage',
  components: {
    FileDialog,
    treeSide,
    pagination,
    SearchCommon
  },
  mixins: [TableMixin],
  props: {
    componentName: {
      default: 'TaskPage',
      type: String
    }
  },
  data() {
    return {
      fileInfo: {},
      fileShowDialog: false,
      multiSelectData: [],
      downloadLoading: false,
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      btnLoading: false,
      treeLoading: true,
      treeItem: {},
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      optionList: [
        {
          title: '巡检人',
          prop: 'r.inspect_users_name_',
          type: 'input',
          default: true
        },
        {title: '巡检队伍', prop: 't.team_name_', type: 'input'},
        {
          title: '巡检状态',
          prop: 't.task_status_',
          type: 'select',
          option: getDictionaryByCode('xc_zt'),
          multiple: true
        }
        // {
        //   title: '巡检类型',
        //   prop: 't.plan_type_',
        //   type: 'select',
        //   option: getDictionaryByCode('xjlx-xjrw'),
        //   multiple: true
        // }
        // {title: '任务时间', prop: 'taskDate', type: 'input', default: true}
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'IN', property: 't.task_status_'},
          {operation: 'IN', property: 't.road_id_'},
          {operation: 'EQUAL', property: 'r.inspect_users_name_'},
          {operation: 'LIKE', property: 't.team_name_'},
          {operation: 'IN', property: 't.plan_type_'},
          {
            operation: 'BETWEEN',
            property: 'taskDate',
            value: [
              moment().subtract(1, 'month')
                .startOf('month')
                .format('YYYY-MM-DD'),
              moment()
                .endOf('month')
                .format('YYYY-MM-DD')
            ]
          }
        ],
        sorter: [
          {direction: 'DESC', property: 't.create_time_'},
          {direction: 'DESC', property: 'taskDate'}
        ]
      }
    }
  },
  computed: {
    statusStyle() {
      return item => {
        switch (item) {
          case 0:
            return '#909399'
          case 1:
            return '#409EFF'
          case 2:
            return '#E6A23C'
          case 3:
            return '#40e2ff'
          case 4:
            return '#67C23A'
          case 5:
            return '#F56C6C'
          default:
            return ''
        }
      }
    }
  },
  created() {
    // 获取树形目录
    this.getOrgTreeData(treeData => {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.treeItem = treeData[0] || {}
      let array = []
      if (this.treeItem.children.length > 0) {
        array = this.extractIds(this.treeItem)
      }
      this.$nextTick(_ => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id)
        this.$refs.treeSide?.expandHandle(true, 2)
      })
      setQueryValue(this.params, 't.road_id_ ', array)
      this.loadData()
    })
  },
  mounted() {
    this.pubSub = PubSub.subscribe('TaskPage', (_, data) => {
    })
  },
  methods: {
    dictionaryEscape,
    getSorterDirection,
    extractIds(node) {
      let ids = []
      // 如果当前节点有 children，则递归提取
      if (node.children) {
        ids = node.children.map(child => child.id) // 提取当前节点的 id
        // 递归提取子节点的 id
        node.children.forEach(child => {
          ids = ids.concat(this.extractIds(child))
        })
      }
      return ids
    },
    filePreviewChange(row) {
      this.fileInfo = row
      this.fileShowDialog = true
    },
    datePickerChange(val) {
      setQueryValue(this.params, 'taskDate', val)
      this.params.pageBean.page = 1
      this.loadData()
    },
    handleSelectionChange(row) {
      this.multiSelectData = row.map(item => item.id)
    },
    async exportData() {
      this.downloadLoading = true
      try {
        let params = {
          groupRelation: 'AND',
          groupTree: {},
          pageBean: {
            page: 1,
            pageSize: -1,
            showTotal: true
          },
          params: {},
          querys: [
            {
              group: 'main',
              operation: 'IN',
              parentGroup: '',
              property: 't.id_',
              relation: 'AND',
              value: this.multiSelectData
            }
          ],
          sorter: [
            {
              direction: 'ASC',
              property: ''
            }
          ]
        }
        const response = await exportDataFile(params)
        // 创建Blob对象
        const blob = new Blob([response], {type: 'application/zip'})
        // 创建下载链接
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl
        // 设置文件名（可以根据需要调整）
        link.setAttribute('download', '日常巡查档案.zip')
        // 触发下载
        document.body.appendChild(link)
        link.click()
        // 清理
        document.body.removeChild(link)
        window.URL.revokeObjectURL(downloadUrl)
        this.$message.success('导出成功')
      } finally {
        this.downloadLoading = false
      }
    },

    offPage() {
    },
    // 获取路段树
    async getOrgTreeData(callback) {
      try {
        this.treeLoading = true
        let {value} = await getTree()
        this.treeData = [value]
      } finally {
        this.treeLoading = false
        callback && callback(this.treeData)
      }
    },
    transformTreeData(data) {
      return {
        name: data.name,
        id: data.id,
        children: data.children.reduce((acc, child) => {
          acc.push({
            id: child.id,
            name: child.name,
            path: child.path,
            children: child.roadList.map(road => ({
              id: road.id,
              name: road.name,
              path: road.path
            }))
          })
          return acc
        }, [])
      }
    },
    //左边树节点
    currentChange(nodeItem) {
      if (nodeItem.id === '1766017468444450816') {
        setQueryValue(this.params, 't.road_id_', this.extractIds(nodeItem))
      } else if (nodeItem.children && nodeItem.children.length > 0) {
        const array = nodeItem.children.map(item => item.id)
        setQueryValue(this.params, 't.road_id_', array)
      } else {
        setQueryValue(this.params, 't.road_id_', [nodeItem?.id] || [])
      }
      // 判断是否是一级目录（有 children 属性）
      // if (nodeItem.children && nodeItem.children.length > 0) {
      //   // this.$message.warning('请选择二级目录进行新增操作')
      //   const array = nodeItem.children.map(item => item.id)
      //   setQueryValue(this.params, 't.road_id_ ', array)
      // } else {
      //   setQueryValue(this.params, 't.road_id_ ', [nodeItem?.id] || [])
      // }
      this.params.pageBean.page = 1
      this.calcTableHeight(500)
      PubSub.publish('TreeItemSelected', nodeItem)
      this.treeItem = nodeItem || {}
      this.loadData()
    },

    //获取数据
    async loadData() {
      try {
        this.tableLoading = true
        const {total = 0, rows = []} = await tableYiChaData(
          refineRequestBody(this.params)
        )
        this.params.pageBean.total = total
        this.tableData = rows
      } finally {
        this.tableLoading = false
      }
    },

    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return
      this.$emit(
        'changePage',
        pageName,
        _ => {
          PubSub.publish(pageName, row)
        },
        '点位查询'
      )
    },
    dakaStyle(row) {
      if (row.taskStatus === 4) {
        if (row.fixedPoint >= row.requestPoint) {
          return '#67C23A'
        } else {
          return '#F56C6C'
        }
      }
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
.table-page {
  .basis {
    min-width: 240px !important;
  }
}
</style>
