<template>
  <div class="app-content">
    <a-drawer title="项目分配" placement="right" :destroyOnClose="true" :closable="true" :visible="drawerVisible" :get-container="false" :wrap-style="{ position: 'absolute' }" @close="onDrawerClose">
      <div class="drawer-content">
        <group-expert-select ref="expertS" :projGroupSelectedRowKeys="projGroupSelectedRowKeys" @close="onDrawerClose" />
      </div>
    </a-drawer>
    <a-form :form="form" :model="searchForm" layout="inline" class="search_form">
      <a-form-item>
        <a-select default-value="" placeholder="分配状态" v-model="searchForm.groupYear" style="width: 160px" @change="handleYearChange">
          <a-select-option v-for="record in YearData" :key="record.year" :value="record.year">
            {{ record.year + '年' }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-input placeholder="项目组名称" v-model="searchForm.groupName" :maxLength="100" style="width: 150px" />
      </a-form-item>
      <a-form-item>
        <a-select default-value="" placeholder="分配状态" v-model="searchForm.assignState" style="width: 160px" @change="handleAssignChange">
          <a-select-option value="">--请选择分配状态--</a-select-option>
          <a-select-option value="1">已分配</a-select-option>
          <a-select-option value="0">未分配</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <para-select v-model="searchForm.knowledgeId" :typeId="56" :width="150" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" icon="search" @click="projSearch">搜索</a-button>
        <a-button icon="reload" style="margin-left: 10px" @click="projReset" class="bt-normal">重置</a-button>
      </a-form-item>
    </a-form>
    <a-divider style="height: 1px; background-color: #e8e8e8;" />
    <div class="submit-btn">
      <a-button icon="plus-circle" type="primary" @click="onAddProjectGroup">添加项目组</a-button>
      <a-button icon="plus-circle" type="primary" @click="onAssignProjectIntoGroup">分配项目进入项目组</a-button>
      <a-button type="primary" @click="onaAssignDetail">分配明细</a-button>
      <a-button icon="download" type="primary" @click="exportEvaluationExcel">项目评审结果导出</a-button>
      <a-button icon="download" type="primary" @click="exportProjGroupScoreExcel">项目分组排名导出</a-button>
      <a-tag :color="technology">{{ '技术专家' }}</a-tag>&nbsp;<a-tag :color="finance">{{ '财务专家' }}</a-tag>
    </div>
    <a-table :dataSource="tableData2" :columns="columns2" rowKey="id" :pagination="false" :loading="loading" :row-selection="{ selectedRowKeys: projGroupSelectedRowKeys, onChange: onProjGroupSelectChange, type: selectType }" @expand="getInnerData" :expandedRowKeys="expandedRowKeys">
      <template slot="groupName" slot-scope="record">
        <a @click="recordClick(record, 'groupView')">{{record.groupName}}</a>
      </template>
      <template slot="assignInfo" slot-scope="record">
        <a-tag v-if="!record.expertList||record.expertList.length===0" :color="'red'">未分配</a-tag>
        <a-tooltip v-else v-for="data in record.expertList" :key="data.id" placement="topLeft">
          <template slot="title">
            <span>{{ data.workUnit }}</span>
          </template>
          <a-tag :color="data.expertType == 1 ? technology : finance" @click="evaluationView(data)">{{data.personName}}</a-tag>
        </a-tooltip>
      </template>
      <template slot="option" slot-scope="record">
        <a-button type="link" size="small" @click="recordClick(record, 'edit')">修改</a-button>
        <a-button type="link" size="small" @click="recordClick(record, 'delete')" v-if="!record.projectList||record.projectList.length===0">删除</a-button>
        <a-button type="link" size="small" @click="recordClick(record, 'assign')" v-if="record.projectList&&record.projectList.length>0">分配专家</a-button>
        <!-- <a-button type="link" size="small" @click="recordClick(record, 'expertView')" v-if="!record.expertList||record.expertList.length!==0">专家明细</a-button> -->
      </template>
      <a-table style="margin:5px" slot="expandedRowRender" size="small" rowKey="index" :columns="innerColumns" :loading="loading" :data-source="innerData" :pagination="false">
        <template slot="option" slot-scope="record">
          <a-button type="link" size="small" @click="knowledgeDelete(record)">删除</a-button>
        </template>
      </a-table>
    </a-table>
    <a-pagination v-if="pagination.total > 0" :total="pagination.total" show-size-changer show-quick-jumper v-model="pagination.pageIndex" :page-size="pagination.pageSize" :page-size-options="pagination.pageSizeOptions" @showSizeChange="showSizeChange" @change="change" :showTotal="() => `共 ${pagination.total} 条`" />

    <a-modal v-model="groupEditVisible" title="项目组编辑" width="60%" :dialog-style="{ top: '15%' }" :maskClosable="false" destroyOnClose>
      <template slot="footer">
        <a-button type="primary" @click="() => this.$refs.childEdit.submit()">提交</a-button>
      </template>
      <group-edit v-model="groupId" @close="closeWindow" ref="childEdit"></group-edit>
    </a-modal>
    <a-modal v-model="evaluationVisible" title="专家查看" width="1000px" :dialog-style="{ top: '15%' }" :footer="null" destroyOnClose>
      <assign-group-expert-view v-model="evaluationId" @close="closeAssignExpertView" />
    </a-modal>
    <a-modal v-model="assignDetailVisible" title="分配明细" width="90%" :dialog-style="{ top: '5%' }" :footer="null" destroyOnClose>
      <assign-detail :groupList="groupList" />
    </a-modal>
    <a-modal v-model="projectIntoGroupVisible" :title="projectIntoGroupTitle" width="70%" :dialog-style="{ top: '8%' }" :maskClosable="false" destroyOnClose>
      <template slot="footer">
        <div style="text-align:center; width:100%">
          <a-button type="primary" @click="() => this.$refs.childEdit.submit()">提交</a-button>
        </div>
      </template>
      <project-select-into-group v-model="groupId" @close="closeProjectIntoGroupWindow" ref="childEdit"></project-select-into-group>
    </a-modal>
    <a-modal v-model="projDetailVisible" :title="projectGroupTitle" width="95%" :dialog-style="{ top: '8%' }" :footer="null" class="custom-modal" destroyOnClose>
      <group-detail v-model="groupId" @close="() =>  this.projDetailVisible = false" />
    </a-modal>
  </div>
</template>

<script>
import { getType } from '@/views/utils/auth'
import { isEmptyParams } from '@/views/utils/common'
import paraSelect from '@/views/components/common/paraSelect'
import groupDetail from '@/views/peAssign/components/groupDetail'
import groupEdit from '@/views/peAssign/components/groupEdit'
import projectGroupAdjust from '@/views/assign/components/projectGroupAdjust'
import groupExpertSelect from '@/views/assign/components/groupExpertSelect'
import assignGroupExpertView from '@/views/assign/components/assignGroupExpertView'
import knowledgeSelect from '@/views/peAssign/components/knowledgeSelect'
import projectStatistic from '@/views/peAssign/components/projectStatistic'
import assignDetail from '@/views/assign/components/assignDetail'
import ProjectSelectIntoGroup from '@/views/peAssign/components/projectSelectIntoGroup.vue'

export default {
  name: "projKeyAssign",
  components: {
    paraSelect, groupDetail, projectGroupAdjust, groupEdit, groupExpertSelect, assignGroupExpertView, knowledgeSelect, projectStatistic, assignDetail, ProjectSelectIntoGroup
  },
  data () {
    return {
      reportYear: null,
      form: this.$form.createForm(this, { name: "projGroupSearch" }),
      YearData: null,
      searchForm: { groupYear: null, groupName: null, knowledgeParentId: null, knowledgeId: null, assignState: '' },
      columns2: [
        { title: "项目分组名称", scopedSlots: { customRender: 'groupName' } },
        { title: "年度", dataIndex: "groupYear", align: 'center' },
        //{ title: "项目分组序号", dataIndex: "displayOrder", align: 'center' },
        { title: "项目数", dataIndex: "projCount", align: 'center' },
        { title: "专家数", dataIndex: "expertCount", align: 'center' },
        { title: '分配信息', scopedSlots: { customRender: 'assignInfo' }, align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'option' }, align: 'center', width: 200 }, //fixed: 'right',
      ],
      tableData2: [],
      pagination: {
        pageIndex: 1,
        pageSize: 100,
        total: 0,
        pageSizeOptions: this.$defaultPageSizeOptions,
      },
      selectType: 'radio',
      expandedRowKeys: [],
      innerColumns: [
        { title: "二级学科", dataIndex: "knowledgeName", align: 'left' },
        { title: "项目数", dataIndex: "projCount", align: 'center' },
        { title: "操作", scopedSlots: { customRender: 'option' }, align: 'center' },
      ],
      innerData: [],
      loading: false,
      projGroupSelectedRowKeys: [],
      projDetailVisible: false,
      groupId: null,
      groupInfo1: null,
      groupInfo2: null,
      groupEditVisible: false,
      drawerVisible: false,
      evaluationVisible: false,
      evaluationId: null,
      projectGroupTitle: '',
      evaluationStatisticVisible: false,
      assignDetailVisible: false,
      eTableData: [],
      eMergeList: [],
      projectIntoGroupVisible: false,
      projectIntoGroupTitle: null,
      technology: "#2db7f5",
      finance: "#87d068",
      groupList: [],
    };
  },
  created () {
    //this.getYear()
    this.getYearInfo()
  },
  methods: {
    isEmptyParams,
    getYearInfo () {
      let pars = { batch: 1, projType: getType() }
      this.$api.batch.getBatchList({ ...pars }).then(({ data = {} }) => {
        if (data) {
          this.YearData = data
          this.getYear()
        }
      }).catch(() => {
      })
    },
    getYear () {
      this.$api.batch.getCurrentYearBatch({ type: 1, projType: getType(), timeType: 1 }).then(({ data = {} }) => {
        if (data) {
          this.reportYear = data.year
          this.searchForm.groupYear = data.year
          this.getListByPage()
        }
      }).catch(() => { })
    },
    getListByPage () {
      this.loading = true
      let pars = isEmptyParams(this.searchForm)
      let par = { ...pars, pageIndex: this.pagination.pageIndex, pageSize: this.pagination.pageSize }
      this.$api.projectGroupAssign.getProjectGroupListByPage(par).then(({ data = {} }) => {
        if (data) {
          const { dataList = [], total = 0 } = data
          this.tableData2 = dataList
          this.pagination.total = total
          this.loading = false
          this.projGroupSelectedRowKeys = []
        } else { this.loading = false }
      }).catch(() => {
        this.loading = false
      })
    },
    change () {
      this.getListByPage()
    },
    showSizeChange (current, pageSize) {
      this.pagination.pageIndex = current
      this.pagination.pageSize = pageSize
      this.getListByPage()
    },
    handleYearChange (value) {
      this.searchForm.groupYear = value
    },
    handleAssignChange (value) {
      this.searchForm.assignState = value
    },
    projSearch () {
      this.getListByPage()
    },
    projReset () {
      this.searchForm = { groupName: null, knowledgeParentId: null, knowledgeId: null, assignState: '', }
      this.getListByPage()
    },
    parChange (value) {
      this.searchForm.knowledgeParentId = value
    },
    onProjGroupSelectChange (selectedRowKeys) {
      this.projGroupSelectedRowKeys = selectedRowKeys
    },
    recordClick (record, type) {
      switch (type) {
        case 'groupView':
          this.projectGroupTitle = '[' + record.groupName + ']-项目组明细'
          this.projDetailVisible = true
          this.groupId = record.id
          break
        case 'edit':
          this.groupEditVisible = true
          this.groupId = record.id
          break
        case 'delete':
          let self = this
          this.$confirm({
            title: '项目组删除',
            content: '确定要删除该项目组？',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk () {
              self.$api.projectGroupAssign.deleteByGroupId({ id: record.id }).then(({ data = {} }) => {
                if (data) {
                  self.$message.success('删除成功！')
                  self.getListByPage()
                }
              })
            },
            onCancel () {
            },
          })
          break
        case 'assign':
          this.projGroupSelectedRowKeys = [record.id]
          this.drawerVisible = true
          break
        case 'expertView':
          break
      }
    },

    onAddProjectGroup () {
      this.groupId = null
      this.groupEditVisible = true
    },
    onaAssignDetail () {
      this.groupList = []
      this.groupList.push({ groupId: "", groupName: "--请选择分组--" })
      this.tableData2.forEach(e => {
        this.groupList.push({ groupId: e.id, groupName: e.groupName })
      })
      this.assignDetailVisible = true
    },
    closeWindow (value) {
      if (value === 'edit') {
        this.groupEditVisible = false
        this.getListByPage()
      }
      // else
      //   this.visibleView = false
    },
    onDrawerClose (value) {
      this.projGroupSelectedRowKeys = []
      this.drawerVisible = false
      if (value === 'assign') {
        this.getListByPage()
      }
      else {

      }
    },
    evaluationColor (record) {
      if (record.gradeScore)
        return 'orange'
      else
        return 'green'
    },
    evaluationView (record) {
      this.evaluationId = record.id
      this.groupId = record.groupId
      this.evaluationVisible = true
    },
    closeAssignExpertView () {
      this.evaluationId = null
      this.groupId = null
      this.evaluationVisible = false
      this.getListByPage()
    },
    closeProjDetail () {
      this.projDetailVisible = false
      this.getListByPage()
    },
    getInnerData (expanded, record) {
      if (record.projCount == 0) {
        this.$message.info('该项目组还没有分配项目！')
        return
      }
      this.expandedRowKeys = []
      this.innerData = []
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        this.getProjectKnowledgeStatistic(record.id)
      }
    },
    getProjectKnowledgeStatistic (groupId) {
      this.loading = true
      this.$api.projectGroupAssign.getProjectKnowledgeStatisticByGroupId({ groupId: groupId }).then(({ data = {} }) => {
        if (data) {
          this.innerData = data
          this.loading = false
        } else { this.loading = false }
      }).catch(() => {
        this.loading = false
      })
    },
    knowledgeDelete (record) {
      let projGroup = this.tableData2.filter(e => e.id === record.groupId)
      if (projGroup[0].expertCount > 0) {
        this.$message.info('该项目组已经分配了专家，不能移除该二级学科下所属项目！')
        return
      }

      let self = this
      this.$confirm({
        title: '',
        content: '确定要从该项目组中移除该二级学科下所属项目？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          self.loading = true
          self.$api.projectGroupAssign.deleteProjectGroupDetail({ groupId: record.groupId, knowledgeId: record.knowledgeId }).then(({ data = {} }) => {
            if (data) {
              if (data === '项目组移除项目成功！') {
                self.$message.success(data)
                self.getListByPage()
                self.getProjectKnowledgeStatistic(record.groupId)
              } else {
                self.$message.info(data)
              }
            }
            self.loading = false
          }).catch(() => { self.loading = false })
        },
        onCancel () { },
      })
    },
    onAssignProjectIntoGroup () {
      if (this.projGroupSelectedRowKeys.length <= 0) {
        this.$message.info('请选择一个项目组！')
        return
      }

      let projGroup = this.tableData2.filter(e => e.id === this.projGroupSelectedRowKeys[0])
      if (projGroup[0].expertCount > 0) {
        this.$message.info('该项目组已经分配了专家，不能再添加二级学科下所属项目！')
        return
      }
      this.projectIntoGroupTitle = '选择项目进入【' + projGroup[0].groupName + '】'

      this.groupId = this.projGroupSelectedRowKeys[0]
      this.projectIntoGroupVisible = true
    },
    closeProjectIntoGroupWindow () {
      this.projectIntoGroupVisible = false
      this.getListByPage()
    },
    exportEvaluationExcel () {
      this.loading = true
      const rowMarks = ['A', 'B', 'C', 'D', 'E', 'P', 'Q']
      
      this.$api.statistical.getEvaluationExportExcel({ 
        reportYear: this.reportYear, 
        startRow: 3, 
        rowMarks: rowMarks 
      }).then(({ data = {} }) => {
        if (data) {
          this.eTableData = data.evaluationList
          this.eMergeList = data.mergeList

          import('@/views/utils/Export2Excel').then(excel => {
            try {
              const multiHeader = [[this.reportYear + '项目评审结果列表', '', '']]
              const header = ['项目编号', '项目名称', '一级学科', '二级学科', '所属市州', '证件号', '专家姓名', '专家单位', '手机号', '专家类型', '专家评分', '评审类别', '评审内容', '评审状态', '总分', '最终得分']
              const filterVal = ['projNo', 'projName', 'parentName', 'knowledgeName', 'unitName', 'certId', 'personName', 'expertUnitName', 'mobile', 'expertTypeName', 'evaluationScore', 'evaluationTypeName',  'remark', 'auditStateName', 'totalScore', 'calculateScore']
              const list = this.eTableData
              const merges = ['A1:Q1'].concat(this.eMergeList)
              const data = list.map(item => filterVal.map(j => item[j]))
              const filename = this.reportYear + '项目评审结果列表'
              
              excel.exportJsonToExcel({
                multiHeader,
                header,
                data,
                merges,
                filename,
                autoWidth: true,
              })
              
              this.$message.success('导出成功')
            } catch (err) {
              console.error('Excel导出错误:', err)
              this.$message.error(`导出失败: ${err.message || '未知错误'}`)
            }
            
            this.loading = false
            this.eTableData = []
            this.eMergeList = []
          }).catch(err => {
            console.error('加载Export2Excel模块错误:', err)
            this.$message.error(`加载导出模块失败: ${err.message || '未知错误'}`)
            this.loading = false
          })
        }
      }).catch(err => {
        console.error('获取评审数据错误:', err)
        this.$message.error(`获取评审数据失败: ${err.message || '未知错误'}`)
        this.loading = false
        this.eTableData = []
        this.eMergeList = []
      })
    },
    exportProjGroupScoreExcel () {
      this.loading = true

      const rowMarks = ['A']
      this.$api.statistical.getProjectGroupScoreOrder({ reportYear: this.reportYear, startRow: 3, rowMarks: rowMarks }).then(({ data = {} }) => {
        if (data) {
          this.eTableData = data.groupScoreList
          //this.eMergeList = data.mergeList

          import('@/views/utils/Export2Excel').then(excel => {
            const multiHeader = [[this.reportYear + '项目分组排名列表', '', '']] // 标题
            const header = ['组名', '组内排名', '项目编号', '项目名称', '一级学科', '二级学科', '申报单位', '申报人', '所属市(州）', '技术专家评分', '财务专家评分', '最终得分'] // 表头
            const filterVal = ['groupName', 'orderNo', 'projNo', 'projName', 'parentName', 'knowledgeName', 'appUnitName', 'personName', 'unitName', 'gradeScore1', 'gradeScore2', 'calculateScore'] // 数据属性
            const list = this.eTableData //请求来的数据
            const merges = ['A1:L1'].concat(this.eMergeList) //需要合并的标题头单元格
            const data = list.map(item => filterVal.map(j => item[j])) // 转换二维数组
            const filename = this.reportYear + '项目分组排名列表'
            excel.exportJsonToExcel({
              multiHeader, // 标题--非必要
              header, // 表头
              data,  // 具体数据--二维数组
              merges, // 合并--非必要
              filename, // 下载文件名
              autoWidth: true,  // 不自动调整列宽
            })
            this.loading = false
            this.eTableData = []
            this.eMergeList = []
          }).catch(() => { this.loading = false })
        }
      }).catch(() => { this.loading = false })
    }
  }
};
</script>

<style scoped lang="less">
.outer-layer {
  margin: 5px;
  height: 100%;
}
.card-head {
  min-height: 30px;
  margin-bottom: -1px;
  padding: 0 5px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  font-size: 16px;
  background: transparent;
  border-bottom: 1px solid #e8e8e8;
  border-radius: 2px 2px 0 0;
  zoom: 1;
  text-align: center;
}
.left-column {
  float: left;
  width: 30%;
  height: 100%;
}
.right-column {
  float: right;
  width: 69.6%;
  height: 100%;
}
.ant-descriptions {
  height: calc(100% - 50px);
}
.ant-descriptions-view {
  overflow-x: hidden;
  overflow-y: scroll;
  height: 100%;
}
.app-content {
  ::v-deep .ant-radio-group {
    margin: 14px 0px 0px 0px !important;
  }
  ::v-deep .ant-drawer .ant-drawer-content-wrapper {
    width: 700px !important;
    .ant-drawer-content .ant-drawer-wrapper-body {
      .ant-drawer-header {
        padding: 10px 10px !important;
        height: 40px;
      }
      .ant-drawer-body {
        height: calc(100% - 40px);
        padding: 0px !important;
      }
    }
  }
  .drawer-content {
    height: 95%;
    width: 100%;
    padding: 3px;
  }
  .ant-tag {
    margin-top: 2px !important;
    margin-right: 5px !important;
    padding: 0 5px !important;
    cursor: pointer;
  }
}

/deep/ .ant-modal-content {
  height: calc(100vh - 150px); /* 设置你想要的高度 */
}
</style>
