<!--
 * @Author: ysh
 * @Date: 2024-02-27 14:49:15
 * @LastEditors: wrh
 * @LastEditTime: 2025-10-14 15:24:21
-->
<template>
  <div class="project-wrapper">
    <!-- 搜索栏 -->
    <el-row>
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="88px">
        <el-form-item label="项目编号" prop="projectNumber">
          <el-input v-model="queryParams.projectNumber" placeholder="请输入项目编号" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="项目负责人" prop="projectLeader">
          <el-select v-model="queryParams.projectLeader" clearable filterable placeholder="请输入项目负责人" size="large"
            style="width: 160px" @keyup.enter.native="handleQuery">
            <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="承担部门" prop="undertakingDept">
          <el-select v-model="queryParams.undertakingDept" filterable clearable @change="handleQuery">
            <el-option v-for="item in $store.state.user.deptList" :key="item.deptId" :label="item.deptName"
              :value="item.deptId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="其他关键字" prop="queryString">
          <el-input v-model="queryParams.queryString" placeholder="请输入关键字" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="isFinished">
          <el-select v-model="queryParams.isFinished" clearable>
            <el-option label="进行中" value="0"></el-option>
            <el-option label="已结束" value="1"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 项目列表 -->
    <el-card style="margin-top: 20px;">
      <div slot="header" class="card-header">
        <div style="font-weight: bold;font-size: 20px;">测绘项目列表</div>
        <div>
          <el-button style="float: right;margin-right: 10px;" type="success" size="mini" icon="el-icon-plus"
            @click="handleRegister">登记项目</el-button>
          <el-button style="float: right;margin-right: 10px;" type="warning" size="mini" icon="el-icon-download"
            @click="handleExport">导出项目</el-button>
        </div>
      </div>
      <el-table v-loading="loading" :data="projectList" style="margin-top: 30px;">
        <el-table-column type="index" width="50">
        </el-table-column>
        <el-table-column prop="isFinshed" align="center" label="状态" width="90px" sortable :sort-method="sortIsFinshed">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isFinished === '0' ? 'success' : 'warning'" disable-transitions>
              {{ scope.row.isFinished == '0' ? '进行中' : '已结束' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="percentage" align="center" label="生产进度" width="120px" sortable>
          <template slot-scope="scope">
            <el-progress :text-inside="true" :stroke-width="26" :status="formatStatus(scope.row.percentage)"
              :percentage="scope.row.percentage" text-color="#fff"></el-progress>
          </template>
        </el-table-column>
        <el-table-column label="项目编号" align="center" key="projectNumber" prop="projectNumber" width="120px" sortable />
        <el-table-column label="项目名称" align="center" key="projectName" prop="projectName" sortable />
        <el-table-column label="合同编码" align="center" prop="contractCode" sortable />
        <el-table-column label="承担部门" align="center" key="undertakingDeptName" prop="undertakingDeptName" sortable />
        <el-table-column label="项目负责人" align="center" key="projectLeaderName" prop="projectLeaderUser.nickName" sortable
          width="120px" />
        <el-table-column label="项目级别" align="center" key="projectLevel" prop="projectLevel" width="120px" sortable>
          <template slot-scope="scope">
            <el-tag :type="scope.row.projectLevel ? (scope.row.projectLevel === '0' ? 'info' : 'danger') : 'info'"
              disable-transitions>
              {{ scope.row.projectLevel ? (scope.row.projectLevel == '0' ? '一般项目' : '重大项目') : '一般项目' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="项目类型" align="center" key="projectType" prop="projectType" width="120px" sortable />
        <el-table-column label="登记日期" align="center" key="registerTime" prop="registerTime" width="120px" sortable >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope" v-if="scope.row.userId !== 1">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
              v-hasPermi="['oa:project:query']">查看</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['oa:project:remove']">删除</el-button>
            <el-button size="mini" type="text" icon="el-icon-document" @click="handleRelate(scope.row)"
              v-hasPermi="['oa:project:relate']">关联合同</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        :autoScroll="false" @pagination="getList" />
    </el-card>
    <el-dialog title="关联合同" :visible.sync="relateOpen" width="60%" append-to-body>
      <choose-contract @choose="confirmContract" @close="relateOpen = false"></choose-contract>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, listProjectFuzzy, submitProject, modifyProject, delProject } from "@/api/oa/project/project";
import { listProjectProgress, getProjectProgress } from "@/api/oa/project/projectProgress";
import { addProjectContract, delProjectContract } from "@/api/oa/contract/projectContract";
import { listDept } from '@/api/system/dept';
import { listUser, getUser } from '@/api/system/user';
import { mapGetters } from 'vuex';
import { checkPermi } from '@/utils/permission';
import { listDefinition } from "@/api/flowable/definition";
import { definitionStart, flowXmlAndNode } from "@/api/flowable/definition";
import { todoList, getNextFlowNodeByStart } from "@/api/flowable/todo";
import { Snowflake } from '@/utils/snowFlake.js'
import chooseContract from '@/views/flowable/form/components/chooseContract.vue';

export default {
  components: { chooseContract },
  name: 'Project',
  computed: {
    ...mapGetters(['deptId', 'userId'])
  },
  data() {
    return {
      userList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectNumber: '',
        projectLeader: undefined,
        projectName: '',
        queryString: undefined,
      },
      projectList: [],
      total: 0,
      loading: true,
      addOpen: false,
      relateOpen: false,
      modifyOpen: false,
      title: '',
      addForm: {},
      rules: {
        projectNumber: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
        projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }]
      },
      peopleVisible: false,
      peopleForm: {
        deptId: '',
        deptList: [],
        userId: '',
        userList: []
      },
      workList: [{
        content: '',
        scale: '',
        unit: '',
        workload: '',
        deadline: '',
        remark: ''
      }],
    }
  },
  created() {
    this.getList();
    this.getDeptList();
    this.getUserList();
  },
  methods: {
    // 查询项目列表
    async getList() {
      this.loading = true
      if (this.deptId > 106 && this.deptId != 109) {
        let response = await checkPermi(['oa:allproject:query'])
        if (response == false) {
          this.queryParams.undertakingDept = this.deptId
        }
      }
      if (this.queryParams.queryString == '' || this.queryParams.queryString == undefined || this.queryParams.queryString == null) {
        listProject(this.queryParams).then(response => {
          this.projectList = response.rows;
          this.total = response.total;
          this.loading = false;
          for (let project of this.projectList) {
            getProjectProgress(project.projectId).then(res => {
              if (res.data) {
                let len = res.data.length
                if (len != 0) {
                  this.$set(project, 'percentage', Number(res.data[len - 1].percentage))
                } else {
                  this.$set(project, 'percentage', 0)
                }
                if (project.isFinished == '1') {
                  this.$set(project, 'percentage', 100)
                }
              }
            })
          }
        })
      }
      else {
        listProjectFuzzy(this.queryParams).then(response => {
          this.projectList = response.rows;
          this.total = response.total;
          this.loading = false;
          for (let project of this.projectList) {
            getProjectProgress(project.projectId).then(res => {
              if (res.data) {
                let len = res.data.length
                if (len != 0) {
                  this.$set(project, 'percentage', Number(res.data[len - 1].percentage))
                } else {
                  this.$set(project, 'percentage', 0)
                }
                if (project.isFinished == '1') {
                  this.$set(project, 'percentage', 100)
                }
              }
            })
          }
        })
      }
    },
    getDeptList() {
      listDept({
        deptName: undefined,
        status: undefined
      }).then(res => {
        this.peopleForm.deptList = res.data
      })
    },
    getUserList() {
      listUser({ pageNum: 1, pageSize: 9999 }).then(res => {
        this.userList = res.rows
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleView(row) {
      let id = row.projectId
      this.$router.push(
        {
          name: 'projectInfo',
          params: { id },
          query: { projectId: id, projectName: row.projectName }
        });
    },
    handleUpdate(row) {
      this.addForm = row;
      this.title = '修改项目信息';
      this.addOpen = true;
    },
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      const projectNumbers = row.projectNumber || this.ids;
      this.$modal.confirm('是否确认删除项目编号为"' + projectNumbers + '"的数据项？').then(function () {
        return delProject(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 关联合同
    handleRelate(row) {
      this.relateOpen = true;
      this.addForm = row
    },
    confirmContract(contract) {
      const projectId = this.addForm.projectId;
      let projectContract = {
        projectId: projectId,
        contractId: contract.contractId
      }
      if (!this.addForm.contract) {
        addProjectContract(projectContract)
      } else {
        delProjectContract(this.addForm.contract.contractId).then(() => {
          addProjectContract(projectContract)
        });
      }
      this.getList();
      this.relateOpen = false;
    },
    confirmAddForm() {
      this.addForm.workList = this.workList;
      let formData = new FormData();
      let form = JSON.stringify(this.addForm);
      formData.append("form", form);
      if (this.title == '新增项目')
        submitProject(formData).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.addOpen = false;
          this.getList();
        });
      else
        modifyProject(formData).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.addOpen = false;
          this.getList();
        });
    },
    // 人员选择
    choosePeople() {
      this.peopleVisible = true;
    },
    // 改变部门选择
    handleChangeDept(deptId) {
      this.peopleForm.userId = '';
      listUser({ pageSize: 999999, deptId }).then(res => {
        this.peopleForm.userList = res.rows
      })
    },
    // 确定项目负责人
    confirmPeople() {
      this.addForm.projectLeader = this.peopleForm.userId;
      this.addForm.projectLeaderName = this.tagLeader()
      this.peopleVisible = false
    },
    tagLeader() {
      if (this.addForm.projectLeader == '' || this.addForm.projectLeader == undefined || this.addForm.projectLeader == null) {
        return undefined
      } else {
        for (let user of this.peopleForm.userList) {
          if (this.addForm.projectLeader == user.userId) {
            return user.nickName
          }
        }
      }
    },
    cancel() {
      this.peopleForm.deptId = '';
      this.peopleForm.userId = '';
      this.addOpen = false;
      this.addForm = {}
    },
    addWorkList() {
      this.workList.push({
        content: '',
        scale: '',
        unit: '',
        workload: '',
        deadline: '',
        remark: ''
      });
    },
    deletWorkItem(index) {
      let arr = this.workList
      if (arr.length == 1) {
        return
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
    },
    cancelChoosePeople() {
      this.peopleForm.deptId = '';
      this.peopleForm.userId = '';
      this.peopleVisible = false;
    },
    formatStatus(row) {
      if (!row) {
        row = 0
        return 'exception'
      }
      if (row <= 20) {
        return 'exception'
      } else if (row > 20 && row <= 50) {
        return 'warning'
      } else if (row > 50 && row <= 80) {
        return null
      } else {
        return 'success'
      }
    },
    async handleRegister() {
      let response = await listDefinition({
        pageNum: 1,
        pageSize: 9999,
        name: "项目流转",
        category: "project",
      })
      if (response.data.total == 1) {
        let obj = response.data.records[0]
        this.$confirm("是否发起项目流转？", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleStartProcess(obj)
        }).catch(() => { });
      }
    },
    handleExport() {
      this.queryParams.pageSize = 99999
      this.download('oa/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`).then(() => {
        this.queryParams.pageSize = 10
      })
    },
    handleStartProcess(row) {
      let formId = new Snowflake(1n, 1n, 0n).nextId().toString();
      getNextFlowNodeByStart({ deploymentId: row.deploymentId, variables: { formId: formId } }).then(res => {
        let data = res.data;
        const variables = {};
        const formData = {};
        formData.disabled = true;
        formData.formBtns = false;
        formData.formId = formId
        if (row.id) {
          variables.variables = formData;
          let routePath = this.getRoutePath(row);
          definitionStart(row.id, JSON.stringify(variables)).then(res => {
            this.$modal.msgSuccess(res.msg);
            let procInstanceId = res.data;
            todoList({
              pageNum: 1,
              pageSize: 99999999, processInsId: procInstanceId
            }).then(toDoRes => {
              let records = toDoRes.data.records;
              if (records.length == 1) {
                records = records[0]
              }
              this.$router.push({
                path: routePath,
                query: {
                  procInsId: records.procInsId,
                  executionId: records.executionId,
                  deployId: records.deployId,
                  taskId: records.taskId,
                  taskName: records.taskName,
                  startUser: records.startUserName + '-' + records.startDeptName,
                  formId: formData.formId,
                  procDefName: records.procDefName
                }
              })
            })
          })
        }
      })
    },
    getRoutePath(row) {
      let path;
      for (let p of this.publicData.pathRoute) {
        if (p.name == row.name) {
          path = p.path
          break
        } else {
          path = '/flowable/task/todo/detail/index'
        }
      }
      return path
    },
    sortIsFinshed(a, b) {
      return Number(a.isFinished) - Number(b.isFinished)
    }
  },
}
</script>

<style lang="scss" scoped>
.project-wrapper {
  padding: 25px;
  background-color: #f5f5f5;
}

.table-header {
  background-color: #f5f5f5;
}

.card-header {
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
}

table {
  /*居中*/
  margin: 0 auto;
  /*边框*/
  /* border: 1px solid black; */
  text-align: center;
  border-collapse: collapse;
  /*设置背景颜色*/
  /* background-color: #bfa; */
}

.static-box {
  width: 100%;
  height: 120px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .title {
    padding-left: 30px;
    padding-top: 10px;
    font-size: 18px;
  }

  .box-content {
    display: flex;

    .box-left {
      padding: 10px;

      .number {
        padding-left: 20px;
        font-size: 36px;
        font-family: Arial, Helvetica, sans-serif;
        line-height: 70px;
        min-width: 100px;
      }
    }

    .box-right {
      flex: 1;
      padding: 0 10px;

      .progress {
        flex: 1;
        padding-left: 10px;
      }
    }
  }

}
</style>