<!--
 * @Author: ysh
 * @Date: 2024-08-16 09:16:36
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-09-05 13:59:35
-->
<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="isFlow ? 18 : 24" :xs="24">
        <h2 class="text-center">项目工作填报表</h2>
        <el-divider></el-divider>
        <div class="mt20 mb20" v-if="showAlter">
          <el-alert title="任务被退回，请修改后重新提交" type="error" :closable="false">
            <return-comment :taskForm="taskForm" @isReturn="isReturn"></return-comment>
          </el-alert>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="110px" :disabled="formDisabled">
          <el-form-item label="是否零星项目：">
            <el-radio-group v-model="radio" @change="chooseLX" :disabled="taskName != '工作填报'">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="项目名称：" prop="projectId" v-if="radio == '0'">
            <el-button icon="el-icon-plus" type="primary" @click="prOpen = true" size="mini"
              v-if="taskName == '工作填报'">选择项目</el-button>
          </el-form-item>
          <el-descriptions class="mb20" border v-if="form.projectId" style="margin-top: 10px" :column="1">
            <el-descriptions-item label="项目编号">
              {{ chooseProject.projectNumber }}
            </el-descriptions-item>
            <el-descriptions-item label="项目名称">
              {{ chooseProject.projectName }}
            </el-descriptions-item>
            <el-descriptions-item label="项目负责人">
              {{ getUserName(chooseProject.projectLeader) }}
            </el-descriptions-item>
          </el-descriptions>
          <el-form-item label="工作类别：" prop="workType">
            <el-select v-model="form.workType" @change="getWorkTypeList(form.workType)" :style="{ width: '100%' }"
              :disabled="taskName != '工作填报'">
              <el-option label="外业" value="外业"></el-option>
              <el-option label="内业" value="内业"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工作细项：" prop="workItem">
            <el-select v-model="form.workItem" :style="{ width: '100%' }" :disabled="taskName != '工作填报'">
              <el-option v-for="item in workTypeList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="具体内容：" prop="workContent">
            <el-input type="textarea" v-model="form.workContent" :autosize="{ minRows: 4, maxRows: 10 }"
              :disabled="taskName != '工作填报'"></el-input>
          </el-form-item>
          <el-form-item label="工作日期：" prop="dateRange">
            <el-date-picker v-model="form.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :disabled="taskName != '工作填报'"
              @change="handleDateRangeChange">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="工天：" prop="workLoad">
            <el-input-number v-model="form.workLoad" @change="countMoney()"
              :disabled="taskName != '工作填报'"></el-input-number>
          </el-form-item>
          <el-row class="text-center">
            <el-col :span="8" :offset="8">
              <p>填报人：<span class="auditor">{{ getUserName(form.userId) }}</span></p>
            </el-col>
            <el-col :span="8">
              <p>填报日期：{{ parseTime(form.submitTime, "{y}-{m}-{d}") }}</p>
            </el-col>
          </el-row>
          <el-form-item label="工天单价：" prop="price" v-if="taskName != '工作填报'">
            <el-tag>{{ form.price }}元 /人天</el-tag>
          </el-form-item>
          <el-form-item label="系数：" prop="coefficient" v-if="taskName != '工作填报'">
            <el-input-number :controls="false" v-model="form.coefficient" @blur="countMoney()"
              :disabled="taskName == '填报人确认'"></el-input-number>
          </el-form-item>
          <el-form-item label="预估绩效：" v-if="taskName != '工作填报'">
            <span class="auditor">{{ money }}（元）</span>
          </el-form-item>
        </el-form>
        <el-row class="text-center mt20" v-if="!formDisabled">
          <el-button type="warning" @click="save" v-if="taskName != '填报人确认'">保 存</el-button>
          <el-button type="danger" @click="returnOpen = true" v-if="taskName != '工作填报' && taskName != '填报人确认'">退
            回</el-button>
          <el-button type="primary" @click="submitForm" v-if="taskName == '工作填报'">提 交</el-button>
          <el-button type="success" @click="approveForm"
            v-if="taskName != '工作填报' && taskName != '填报人确认'">审核通过</el-button>
          <el-button type="primary" @click="confirmForm" v-if="taskName == '填报人确认'">确 认</el-button>
        </el-row>
      </el-col>
      <el-col :span="6" :xs="24" v-if="isFlow">
        <el-card>
          <h2 style="text-align: center;">流程进度</h2>
          <div>
            <flow :flowData="flowData" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title="选择项目" :visible.sync="prOpen" :width="deviceWidth" append-to-body>
      <choose-project @chooseProject="confirmProject"></choose-project>
    </el-dialog>

    <el-dialog title="退回" :visible.sync="returnOpen" width="40%" append-to-body>
      <return-btn :taskForm="taskForm" @goBack="$emit('goBack')" @saves="" @cancel="returnOpen = false"></return-btn>
    </el-dialog>
  </div>
</template>

<script>
import flow from '@/views/flowable/task/todo/detail/flow';
import { flowXmlAndNode } from "@/api/flowable/definition";
import { listPrice, getWorkTypeList, getWorkItemList } from '@/api/oa/price/price'
import { listDeclare, getDeclare, addDeclare, updateDeclare } from '@/api/oa/declare/declare';
import { listProject, getProject } from "@/api/oa/project/project";
import { mapState } from 'vuex';
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import chooseProject from '../components/chooseProject.vue';
import { parseTime } from "@/utils/ruoyi";
import { getUsersDeptLeader, getUsersDeptLeaderByDept, getUsersManageLeaderByDept } from "@/api/system/post.js";
import ReturnComment from "@/views/flowable/form/components/flowBtn/returnComment.vue";
import ReturnBtn from "@/views/flowable/form/components/flowBtn/returnBtn.vue";
export default {
  components: {
    flow,
    chooseProject,
    ReturnComment,
    ReturnBtn
  },
  computed: {
    ...mapState({
      device: state => state.app.device,
    })
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    isFlow: {
      type: Boolean,
      default: true
    },
    formDisabled: {
      type: Boolean,
      default: false
    }
  },
  created() {
    this.initForm();
    if (this.device == 'mobile') {
      this.isFlow = false;
      this.deviceWidth = '450px'
    } else {
      this.deviceWidth = '70%'
    }
    if (this.isFlow) {
      flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
        this.flowData = res.data;
      })
    }
  },
  data() {
    return {
      deviceWidth: '400px',
      flowData: {},
      form: {
        workLoad: 1,
        coefficient: 1,
        price: 200,
        userId: undefined,
        submitTime: undefined,
        beginDate: undefined,
        endDate: undefined,
        dateRange: [],
      },
      radio: '0',
      rules: {
        projectId: [
          { required: true, trigger: "blur", message: "请选择项目" },
        ],
        workType: [
          { required: true, trigger: "change", message: "请选择工作类别" },
        ],
        workItem: [
          { required: true, trigger: "change", message: "请选择工作细项" },
        ],
        workContent: [
          { required: true, trigger: "blur", message: "请填写具体内容" },
        ],
        dateRange: [
          { required: true, trigger: "change", message: "请选择工作日期范围" },
        ]
      },
      prOpen: false,
      chooseProject: {},
      workTypeList: [],
      workItemList: [],
      projectList: [],
      hasForm: false,
      money: 0,
      showAlter: true,
      returnOpen: false
    }
  },
  methods: {
    initForm() {
      if (this.taskName == '工作填报') {
        this.$set(this.form, 'userId', this.$store.state.user.id)
        this.form.submitTime = parseTime(new Date(), "{y}-{m}-{d}")
      }
      listProject({ pageSize: 20 }).then(res => {
        this.projectList = res.rows
      })
      getDeclare(this.taskForm.formId).then(res => {
        if (res.data) {
          this.form = res.data;
          this.form.price = 200;
          this.hasForm = true;
          this.countMoney();

          // 设置日期范围
          if (res.data.beginDate && res.data.endDate) {
            this.form.dateRange = [res.data.beginDate, res.data.endDate];
          }

          if (!res.data.projectId) {
            this.radio = '1'
          } else {
            getProject(res.data.projectId).then(res => {
              if (res.data) {
                this.chooseProject = res.data
              }
            })
            this.getWorkItemList(this.form.workType);
          }

        }
      })
    },
    async save() {
      if (this.hasForm) {
        let updateRes = await updateDeclare(this.form);
      } else {
        this.form.formId = this.taskForm.formId;
        let addRes = await addDeclare(this.form);
        this.$router.go(0)
      }
      this.$message.success('保存成功');
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$set(this.taskForm.variables, "skip", false);
          if (!this.chooseProject.projectLeader) {
            if (this.radio == '0') {
              this.$message.error('该项目未指定项目负责人，无法提交。')
              return
            }
          }
          this.$confirm('是否确认提交表单？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            if (this.radio == '0') {
              let approval = this.chooseProject.projectLeader;
              this.$set(this.taskForm.variables, "approval", approval);
            } else {
              let resData = await getUsersDeptLeader({ userId: this.form.userId });
              if (resData.data) {
                this.$set(this.taskForm.variables, "approval", resData.data.userId);
                this.$set(this.taskForm.variables, "skip", true);
              }
            }
            if (this.hasForm) {
              updateDeclare(this.form);
            } else {
              this.form.formId = this.taskForm.formId;
              addDeclare(this.form);
            }
            console.log(this.taskForm);
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(() => {
              this.handleComplete(this.taskForm);
            })
          })
        } else {
          this.$message.error('请完善必填项');
        }
      })
    },
    async approveForm() {
      const params = { taskId: this.taskForm.taskId };
      if (this.taskName == '项目负责人审核') {
        this.form.checkStatus = '1';
        updateDeclare(this.form);
        let resData = await getUsersDeptLeader({ userId: this.form.userId });
        if (resData.data) {
          this.$set(this.taskForm.variables, "approval", resData.data.userId);
          getNextFlowNode(params).then(() => {
            this.handleComplete(this.taskForm);
          })
        }
      } else if (this.taskName == '部门负责人审核') {
        this.form.checkStatus = '1';
        this.form.auditStatus = '1';
        updateDeclare(this.form);
        this.$set(this.taskForm.variables, "approval", this.form.userId);
        getNextFlowNode(params).then(() => {
          this.handleComplete(this.taskForm);
        })
      }
    },
    confirmForm() {
      this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？').then(() => {
        this.form.confirmStatus = '1';
        updateDeclare(this.form);
        const params = { taskId: this.taskForm.taskId };
        getNextFlowNode(params).then(() => {
          this.handleComplete(this.taskForm);
        })
      })
    },
    handleComplete(taskForm) {
      complete(taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.$emit('goBack');
      })
    },
    countMoney() {
      let result = parseFloat(this.form.price * this.form.workLoad * this.form.coefficient)
      this.money = result.toFixed(2)
    },
    confirmProject(val) {
      if (val.length != 1) {
        this.$message.error("项目只能选择一个！");
        return;
      }
      this.chooseProject = val[0]
      this.$set(this.form, 'projectId', val[0].projectId)
      this.prOpen = false;
      this.$refs.form.validateField('projectId');
    },
    /* 获取工作类别 */
    getWorkTypeList(workType) {
      listPrice({ workType: workType, pageNum: 1, pageSize: 9999 }).then(res => {
        if (res.code == 200) {
          let data = res.rows;
          let list = [];
          for (let d of data) {
            list.push(d.workItem)
          }
          if (workType == '内业') {
            list.push('其他')
          }
          this.workTypeList = this.setArray(list);
        }
      })
    },
    /* 获取工作项目 */
    getWorkItemList(workType) {
      getWorkItemList({ workType: workType }).then(res => {
        if (res) {
          let workItemList = this.setArray(res);
          this.workItemList = workItemList;
        }
      })
    },
    // 数组去重，并格式化为label、value形式
    setArray(arr) {
      if (arr != [] && arr != undefined) {
        let datalist = [...new Set(arr)];
        let list = [];
        for (let i of datalist) {
          let obj = new Object();
          obj.label = i;
          obj.value = i;
          list.push(obj);
        }
        return list;
      } else {
        return [];
      }
    },
    remoteMethod(val) {
      listProject({
        pageNum: 1,
        pageSize: 20,
        projectNumber: val
      }).then(res => {
        this.projectList = res.rows;
      })
    },
    chooseLX(val) {
      if (val == '1') {
        this.rules = {
          workType: [
            { required: true, trigger: "change", message: "请选择工作类别" },
          ],
          workItem: [
            { required: true, trigger: "change", message: "请选择工作细项" },
          ],
          workContent: [
            { required: true, trigger: "blur", message: "请填写具体内容" },
          ],
          dateRange: [
            { required: true, trigger: "change", message: "请选择工作日期范围" },
          ]
        }
      } else {
        this.rules = {
          projectId: [
            { required: true, trigger: "blur", message: "请选择项目" },
          ],
          workType: [
            { required: true, trigger: "change", message: "请选择工作类别" },
          ],
          workItem: [
            { required: true, trigger: "change", message: "请选择工作细项" },
          ],
          workContent: [
            { required: true, trigger: "blur", message: "请填写具体内容" },
          ],
          dateRange: [
            { required: true, trigger: "change", message: "请选择工作日期范围" },
          ]
        }
      }
    },
    handleDateRangeChange(val) {
      if (val) {
        this.form.beginDate = val[0];
        this.form.endDate = val[1];
        this.calculateWorkDays();
      } else {
        this.form.beginDate = undefined;
        this.form.endDate = undefined;
        this.form.workLoad = 1; // 如果取消选择，则重置工天为1
        this.countMoney();
      }
    },
    // 计算工天
    calculateWorkDays() {
      if (this.form.beginDate && this.form.endDate) {
        const beginDate = new Date(this.form.beginDate);
        const endDate = new Date(this.form.endDate);

        if (endDate >= beginDate) {
          // 计算天数差值，加1是因为要包含开始和结束日期
          const timeDiff = endDate.getTime() - beginDate.getTime();
          const dayDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;

          this.form.workLoad = dayDiff;
          // 重新计算金额
          this.countMoney();
        }
      }
    },
    isReturn(val) {
      this.showAlter = val;
    },
  },
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/element-reset.scss";
</style>