<template>
  <basic-container>
    <!-- 重点工作管理 -->
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model="form"
      v-model:page="page"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-left>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </template>
      <template #menu="{ row }">
        <el-button type="text" @click="handleView(row)">详情</el-button>
        <el-button type="text" @click="handleEdit(row)">修改</el-button>
        <el-button type="text" v-if="row.status == 1" @click="checkRow(row)">审核</el-button>
        <el-button type="text" @click="deleteRow(row)">删除</el-button>
      </template>
      <template #userName="{ row }">{{ row.projectHead.userName }}</template>
      <template #touchingMan="{ row }">{{ row.touchingMan.userName }}</template>
      <template #tsName="{ row }">{{ row.touchingDept.tsName }}</template>
      <!-- 列表嵌套表格 -->
      <template #expand="{ row }">
        <el-table :data="row.stoneList">
          <el-table-column label="里程碑计划" align="center" prop="milestonePlan"></el-table-column>
          <el-table-column
            label="里程碑负责人"
            align="center"
            prop="milestoneMan"
          ></el-table-column>
          <el-table-column
            label="里程碑输出物"
            align="center"
            prop="outputMaterial"
          ></el-table-column>
          <el-table-column
            label="里程碑节点"
            width="200"
            align="center"
            prop="milestoneNode"
          ></el-table-column>
          <el-table-column align="center" label="执行类型" prop="executeType"></el-table-column>
          <el-table-column align="center" label="状态" prop="statusTitle"></el-table-column>
          <el-table-column align="center" label="延期时间" prop="delayTime"></el-table-column>
          <el-table-column
            align="center"
            label="核查结果"
            prop="checkResultTitle"
          ></el-table-column>
          <el-table-column align="center" label="核查人" prop="checkMan.userName"></el-table-column>
          <el-table-column align="center" label="评价等级" prop="gradeTitle"></el-table-column>
          <el-table-column align="center" label="评价人" prop="gradeMan.userName"></el-table-column>
          <el-table-column align="center" label="业务领导评价" prop="evaluate"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                type="text"
                v-if="scope.row.status == 3"
                @click="executeRow(row, scope.row)"
                >执行</el-button
              >
              <el-button type="text" v-if="scope.row.status == 4" @click="auditRow(row, scope.row)"
                >核查</el-button
              >
              <el-button
                type="text"
                v-if="scope.row.status == 6"
                @click="examineRow(row, scope.row)"
                >核准</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    </avue-crud>
    <!-- 新增弹窗 -->
    <add-dialog
      :title="title"
      :visible="addDialogVisible"
      :add-form="addForm"
      @close="addDialogVisible = false"
      @submit-form="submitForm"
    ></add-dialog>
    <!-- 审核弹窗 -->
    <el-dialog v-model="checkDialog" title="审核" append-to-body width="30%">
      <el-form ref="checkForm" :model="checkForm" :rules="checkRules" label-width="80px">
        <el-form-item label="审核结果" prop="checkResult">
          <el-radio-group v-model="checkForm.checkResult">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="checkDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitCheck">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 执行/核查/核准弹窗 -->
    <el-dialog append-to-body :title="subTitle" v-model="executeDialog">
      <el-form :model="executeForm" :rules="executeRules" ref="executeForm" label-width="100">
        <el-form-item label="项目名称">
          <el-input disabled v-model="detailForm.projectName"></el-input>
        </el-form-item>
        <el-form-item label="项目负责人">
          <el-input disabled v-model="detailForm.projectHead.userName"></el-input>
        </el-form-item>
        <el-form-item label="里程碑计划">
          <el-input disabled v-model="executeForm.milestonePlan"></el-input>
        </el-form-item>
        <el-form-item label="里程碑负责人">
          <el-input disabled v-model="executeForm.milestoneMan.userName"></el-input>
        </el-form-item>
        <el-form-item label="项目目标">
          <el-input disabled v-model="executeForm.fmProjectApplication.projectTarget"></el-input>
        </el-form-item>
        <el-form-item label="预期效果">
          <el-input disabled v-model="executeForm.fmProjectApplication.desiredResult"></el-input>
        </el-form-item>
        <el-form-item label="项目背景">
          <el-input disabled v-model="executeForm.fmProjectApplication.projectBackcloth"></el-input>
        </el-form-item>
        <el-form-item label="里程碑节点">
          <el-input disabled v-model="executeForm.milestoneNode"></el-input>
        </el-form-item>
        <el-form-item label="执行类型" prop="executeResult">
          <el-select
            :disabled="subTitle == '核查' || subTitle == '核准'"
            v-model="executeForm.executeResult"
          >
            <el-option label="延期" :value="1"></el-option>
            <el-option label="终止" :value="2"></el-option>
            <el-option label="完成" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="延期时间" v-if="executeForm.executeResult == 1">
          <el-date-picker
            :disabled="subTitle == '核查' || subTitle == '核准'"
            style="width: 100%"
            v-model="executeForm.delayTime"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="里程碑描述" prop="milestoneMemo">
          <el-input
            :disabled="subTitle == '核查' || subTitle == '核准'"
            type="textarea"
            v-model="executeForm.milestoneMemo"
          ></el-input>
        </el-form-item>
        <el-form-item label="里程碑进展" prop="evolve">
          <el-input
            :disabled="subTitle == '核查' || subTitle == '核准'"
            type="textarea"
            v-model="executeForm.evolve"
          ></el-input>
        </el-form-item>
        <el-form-item label="下一步计划" prop="lastPlan">
          <el-input
            :disabled="subTitle == '核查' || subTitle == '核准'"
            type="textarea"
            v-model="executeForm.lastPlan"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="附件"
          v-if="subTitle == '执行' || subTitle == '核查' || subTitle == '核准'"
        >
          <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            :limit="3"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">不能上传 exe 附件，且不超过 20M</div>
          </el-upload>
          <div v-if="subTitle == '核查' || subTitle == '核准'" class="attachment-list">
            <h4>附件下载</h4>
            <ul>
              <li v-for="(file, index) in existingFiles" :key="index">
                <a href="javascript:void(0)" @click="downloadFile(file)">{{ file.name }}</a>
                <el-button type="text" size="small" @click="removeExistingFile(index)"
                  >删除</el-button
                >
              </li>
            </ul>
          </div>
        </el-form-item>
        <el-form-item label="核查人" v-if="subTitle == '执行'">
          <el-select v-model="executeForm.userId">
            <el-option label="审核人一" value="1"></el-option>
            <el-option label="审核人二" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="核查结果" v-if="subTitle == '核查'">
          <el-select v-model="executeForm.checkResult">
            <el-option label="通过" value="1"></el-option>
            <el-option label="不通过" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核人" v-if="subTitle == '核查' && executeForm.checkResult == 1">
          <el-select v-model="executeForm.userId">
            <el-option label="审核人一" value="1"></el-option>
            <el-option label="审核人二" value="2"></el-option>
          </el-select>
        </el-form-item>
        <div v-if="subTitle == '核准'" style="color: #ffc300; margin-bottom: 10px">
          评价等级分为:优(95以上，节点推进超前、完成质量高)、良(85-95分，节点推进正常、质量较好)、中(75-84，节点推进轻微拖期，完成质量一般)、差(75以下，进展滞后，完成质量较差)
        </div>
        <el-form-item v-if="subTitle == '核准'" label="评价分数">
          <el-input v-model="executeForm.score"></el-input>
        </el-form-item>
        <el-form-item v-if="subTitle == '核准'" label="评语">
          <el-input type="textarea" v-model="executeForm.evaluate"></el-input>
        </el-form-item>

        <el-form-item label="审核意见" prop="checkOpinion" label-width="80px">
          <el-input
            type="textarea"
            placeholder="请输入审核意见"
            v-model="checkForm.checkOpinion"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="executeDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitExecute">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getProcessList,
  addProcess,
  updateProcess,
  delProcess,
} from '../../api/flowManagement/index';
import AddDialog from './addDialog.vue';

export default {
  components: { AddDialog },
  data() {
    return {
      // 状态
      // 0-立项待提交、1-立项待审核、2-立项审批不通过、3-项目进行中、
      // 4-项目待核查、5-项目核查不通过、6-项目待核准、7-项目核准不通过、
      // 8-项目已核准
      addDialogVisible: false, // 新增弹窗显隐控制
      title: '新增',
      loading: false,
      title: '新增',
      checkDialog: false,
      subTitle: '执行',
      detailForm: {},
      checkForm: {},
      detailListSelectList: [],
      checkRules: {
        checkResult: [{ required: true, message: '请选择审核结果', trigger: 'blur' }],
      },
      executeDialog: false,
      executeForm: {},
      executeRules: {
        executeResult: [{ required: true, message: '请选择执行类型', trigger: 'blur' }],
        milestoneMemo: [{ required: true, message: '请填写里程碑描述', trigger: 'blur' }],
        evolve: [{ required: true, message: '请填写里程碑进展', trigger: 'blur' }],
        lastPlan: [{ required: true, message: '请填写下一步计划', trigger: 'blur' }],
      },
      data: [],
      form: {},
      existingFiles: [], // 已有附件列表
      addForm: {},
      
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        columnSort: true,
        tip: false,
        expand: true,
        rowKey: 'id',
        height: 'auto',
        align: 'center',
        calcHeight: 32,
        simplePage: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: false,
        selection: false,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        editBtnText: '修改',
        addBtn: false,
        labelWidth: 120,
        menu: true,
        menuWidth: 200,
        dialogWidth: 600,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: true,
        gridBtn: false,
        searchShowBtn: false,
        showOverflowTooltip: true,
        searchLabelPosition: 'left',
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: 'left',
        gridBtn: false,
        searchMenuPosition: 'right',
        addBtnIcon: ' ',
        viewBtnIcon: ' ',
        delBtnIcon: ' ',
        editBtnIcon: ' ',
        searchShowBtn: false,

        column: [
          {
            label: '单据号',
            prop: 'paCode',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: true,
          },
          {
            label: '项目名称',
            prop: 'projectName',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: true,
          },
          {
            label: '项目负责人',
            prop: 'projectHead',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: true,
          },
          {
            label: '项目开始时间',
            prop: 'projectStartTime',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '项目预期结束时间',
            prop: 'projectDesiredEnd',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '制单人',
            prop: 'touchingMan',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '制单部门',
            prop: 'touchingDept',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '制单时间',
            prop: 'touchingTime',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '状态',
            prop: 'approvalStatus',
            span: 24,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
        ],
      },
      rowItem: {}, //存储每一行的数据
    };
  },
  mounted() {},
  methods: {
    insertEvent() {
      // 插入一行
      this.addForm.stoneList.push({});
    },
    openDialog() {
      // 添加新的里程碑行
      const newRow = {
        status: 3,
        statusTitle: '待执行',
        checkMan: null,
        checkResult: 0,
        checkResultTitle: '未核查',
        checkTime: null,
        delayDate: false,
        delayTime: null,
        evaluate: null,
        evolve: '',
        executeResult: 0,
        executeResultTitle: '无',
        grade: 0,
        gradeMan: null,
        gradeTitle: '未评价',
        keyValue: Date.now(),
        lastPlan: '',
        milestoneMan: {
          accountId: null,
          userId: null,
          userName: '',
        },
        milestoneMemo: '',
        milestoneNode: '',
        milestonePlan: '',
        okTime: null,
        outputMaterial: '',
        paIndex: (this.addForm.stoneList?.length || 0) + 1,
        pmId: this.addForm.paId,
        score: null,
        updateMan: null,
      };

      if (!this.addForm.stoneList) {
        this.addForm.stoneList = [];
      }
      this.addForm.stoneList.push(newRow);
      this.$message.success('插入成功');
    },
    handleAdd() {
      this.title = '新增';
      this.addForm = {
        bsBasicClass: {
          bcId: '',
        },
        touchingDept: {
          tsId: '',
        },
        projectHead: {
          userId: '',
        },
        projectSupportMan: {
          userId: '',
        },
      };
      this.addDialogVisible = true;
    },
    // 查看详情
    handleView(row) {
      this.title = '详情';
      this.addForm = row;
      this.addDialogVisible = true;
    },
    // 修改
    handleEdit(row) {
      this.addForm = row;
      this.title = '修改';
      this.addDialogVisible = true;
    },
    // 删除
    deleteRow(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(res => {
        delProcess({ ids: row.id }).then(res => {
          this.$message.success('删除成功');
          this.onLoad(this.page, this.query);
        });
      });
    },
    // 新增/编辑确定
    submitForm() {
      this.loading = true;
      this.addDialogVisible = false;
      this.onLoad(this.page);
    },

    // 审核立项
    checkRow(row) {
      this.checkDialog = true;
      this.rowItem = row;
    },
    //确定审核立项
    submitCheck() {
      this.$refs.checkForm.validate(valid => {
        if (valid) {
          let query = {
            id: this.rowItem.id,
            approvalStatus: this.checkForm.checkResult == 1 ? 3 : 2,
          };
          updateProcess(query).then(res => {
            this.checkDialog = false;
            this.onLoad(this.page);
          });
        }
      });
    },
    // 执行
    executeRow(row, detail) {
      this.executeForm = {};
      this.detailForm = row;
      this.subTitle = '执行';
      this.executeDialog = true;
    },
    // 确定执行
    submitExecute() {
      this.$refs.executeForm.validate(valid => {
        if (valid) {
          this.executeDialog = false;
        }
      });
    },
    // 核查
    auditRow(row, detail) {
      this.subTitle = '核查';
      this.detailForm = row;
      this.executeForm = detail;
      this.executeForm.checkResult = '';
      // 模拟加载已有附件
      this.existingFiles = [
        { name: '项目计划书.pdf', url: '#' },
        { name: '进度报告.docx', url: '#' },
      ];
      this.executeDialog = true;
    },
    // 核准
    examineRow(row, detail) {
      this.subTitle = '核准';
      this.detailForm = row;
      this.executeForm = detail;
      // 模拟加载已有附件
      this.existingFiles = [
        { name: '项目计划书.pdf', url: '#' },
        { name: '进度报告.docx', url: '#' },
        { name: '验收单.xlsx', url: '#' },
      ];
      this.executeDialog = true;
    },
    // 下载附件
    downloadFile(file) {
      const link = document.createElement('a');
      link.href = file.url;
      link.download = file.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 删除已有附件
    removeExistingFile(index) {
      this.$confirm('确定删除该附件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.existingFiles.splice(index, 1);
          this.$message.success('删除成功');
        })
        .catch(() => {});
    },
    delTable(index) {
      this.$confirm('确定删除该条数据么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.addForm.stoneList.splice(index, 1);
          this.$message.success('删除成功');
        })
        .catch(() => {});
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getProcessList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(
        res => {
          this.data = res.data.data.records;
          this.loading = false;
          this.page.total = res.data.data.total;
        }
      );
    },
  },
};
</script>

<style scoped>
.attachment-list {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
}

.attachment-list h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #606266;
}

.attachment-list ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
}

.attachment-list li {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.attachment-list li:last-child {
  border-bottom: none;
}

.attachment-list a {
  color: #409eff;
  text-decoration: none;
}

.attachment-list a:hover {
  color: #66b1ff;
  text-decoration: underline;
}
</style>
