<!--
 * @Author: ysh
 * @Date: 2024-06-21 18:51:54
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-01-23 14:20:57
-->
<template>
  <div>
    <div class="app-container">
      <h2 style="text-align: center">项目运作情况</h2>
      <div class="headers">
        基本作业情况记录
        <div class="line"></div>
      </div>
      <el-form ref="progress" :model="form" :disabled="disabled" label-width="100px">
        <el-form-item label="参与人员：">
          <el-select v-model="participates" multiple disabled style="width:84%">
            <el-option v-for="item in $store.state.user.userList" :label="item.nickName" :value="item.userId"
              :key="item.userId">
            </el-option>
          </el-select>
          <el-button class="ml10" @click="openPeople = true" type="primary" size="mini" icon="el-icon-plus"></el-button>
          <div v-if="participates.length == 0" style="color:#F56C6C">tips:请选择参与人员</div>
        </el-form-item>
        <el-form-item label="驾驶员：">
          <el-tooltip class="item" effect="dark" content="直接获取用车申请中的驾驶员,若无驾驶员,则需要先提交项目的用车申请" placement="top-end">
            <el-select v-model="form.drivers" multiple disabled style="width:90%">
              <el-option v-for="item in $store.state.user.userList" :label="item.nickName" :value="item.userId"
                :key="item.userId">
              </el-option>
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="使用车辆：">
          <el-tooltip class="item" effect="dark" content="直接获取用车申请中的车辆,若无车辆,则需要先提交项目的用车申请" placement="top-end">
            <el-select v-model="form.cars" multiple disabled style="width:90%">
              <el-option v-for="item in carList"
                :label="item.licensePlate + (item.brand ? item.brand : '') + (item.series ? item.series : '')"
                :value="item.carId" :key="item.carId">
              </el-option>
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="使用设备：">
          <el-tooltip class="item" effect="dark" content="直接获取设备申请中的设备,若无设备,则需要先提交项目的设备申请" placement="top-end">
            <el-select v-model="form.devices" multiple disabled style="width:90%">
              <el-option v-for="item in deviceList" :key="item.deviceId" :label="item.name + '【' + (item.brand != null ? item.brand : '') + (item.series != null ? '-' + item.series + '】' : '')
                + (item.code != null ? '（设备编号：' + item.code + '）' : '') + '📍' + item.place" :value="item.deviceId">
              </el-option>
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="进场时间：">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.entryTime"
                value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="撤场时间：">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.exitTime"
                value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="项目进度：">
          <table border="1" style="width:100%">
            <tr>
              <td style="width: 80px">序号</td>
              <td>截至日期</td>
              <td>累计总进度（%）</td>
              <td style="width: 300px">情况说明</td>
              <td style="width: 80px">操作</td>
            </tr>
            <tr v-for="(progress, index) in progressList" :key="index">
              <td>
                {{ index + 1 }}
              </td>
              <td>
                <el-date-picker type="date" placeholder="选择日期" v-model="progress.date"
                  value-format="yyyy-MM-dd"></el-date-picker>
              </td>
              <td>
                <el-input-number v-model="progress.percentage" :controls="false"
                  style="width: 120px"></el-input-number>%
              </td>
              <td>
                <el-input v-model="progress.situation" type="textarea"></el-input>
              </td>
              <td>
                <div class="delete-btn" @click="deleProgressItem(index)">
                  <i class="el-icon-circle-close"></i>
                </div>
              </td>
            </tr>
          </table>
          <el-button icon="el-icon-plus" size="mini" @click="addProgressList()" type="primary" plain></el-button>
        </el-form-item>
        <el-divider></el-divider>
        <actual-work ref="actualRef" :projectId="taskForm.formId"></actual-work>
      </el-form>
      <el-divider></el-divider>
      <div class="headers">
        项目借款
        <div class="line"></div>
        <borrow-data :taskForm="taskForm" :taskName="taskName"></borrow-data>
      </div>

      <div class="headers">
        成果汇交
        <div class="line"></div>
        <achi-data :taskForm="taskForm" :taskName="taskName"></achi-data>
      </div>
      <div class="headers">
        产值结算（内部）
        <div class="line"></div>
        <settle-data :taskForm="taskForm" :taskName="taskName"></settle-data>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="danger" @click="$emit('returnBack')" :disabled="disabled">退 回</el-button>
        <el-button @click="preserve()" :disabled="disabled" type="warning">保 存</el-button>
        <el-button type="primary" @click="submitNextFlow()" :disabled="disabled">项目结束</el-button>
      </div>
    </div>
    <!-- 选择人员对话框 -->
    <el-dialog title="选择人员" :visible.sync="openPeople" width="700px" append-to-body>
      <choosePeople @chooseUser="getChooseUser"></choosePeople>
    </el-dialog>
    <!-- 选择车辆对话框 -->
    <el-dialog title="选择车辆" :visible.sync="openCar" width="700px" append-to-body>
      <choose-car @chooseList="getChooseCar"></choose-car>
    </el-dialog>
    <!-- 选择司机对话框 -->
    <el-dialog title="选择驾驶员" :visible.sync="openDriver" width="700px" append-to-body>
      <choosePeople :deptId="200" @chooseUser="getChooseDriver"></choosePeople>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { parseTime } from "@/utils/ruoyi";
import { complete, rejectTask, returnList, returnTask, getNextFlowNode, delegate, flowTaskForm } from "@/api/flowable/todo";
import { listProjectProgress, getProjectProgress, addProjectProgress, delProjectProgress } from "@/api/oa/project/projectProgress";
import { listProjectWorkload, getProjectWorkload, addProjectWorkload, updateProjectWorkload, delProjectWorkload } from '@/api/oa/project/projectWorkload'
import { getProject, updateProject } from "@/api/oa/project/project";
import { getCar } from "@/api/oa/car/car";
import { listCarApproval, getCarApproval } from '@/api/oa/car/carApproval';
import { listUser } from '@/api/system/user';
import { listCar } from '@/api/oa/car/car';
import { listDevice, getDevice } from "@/api/oa/device/device";
import { listDeviceApproval } from "@/api/oa/device/deviceApproval"
import borrowData from '../inProgress/borrowData.vue';
import SettleData from '../inProgress/settleData.vue';
import ChoosePeople from '../budget/components/choosePeople.vue';
import ChooseCar from '../budget/components/chooseCar.vue';
import ChooseDevice from "../budget/components/chooseDevice.vue";
import AchiData from '../inProgress/achiData.vue';
import actualWork from '@/views/flowable/form/projectProcess/actualWork.vue';
export default {
  components: {
    borrowData,
    SettleData,
    ChoosePeople,
    ChooseCar,
    AchiData,
    actualWork
  },
  computed: {
    ...mapGetters(["name", "userId"]),
  },
  props: {
    disabled: {
      type: Boolean,
      require: true,
    },
    taskForm: {
      type: Object,
      required: true,
    },
    taskName: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      loading: true,
      openPeople: false,
      openDriver: false,
      openCar: false,
      form: {
        licensePlate: "",
        drivers: [],
        cars: [],
        participates: [],
        staff: "",
        entryTime: "",
        exitTime: "",
      },
      rules: {
        manageComment: [{ required: true, message: "请输入审核意见", trigger: "blur" }],
      },
      progressList: [
        {
          date: "",
          percentage: "",
          situation: "",
        },
      ],
      oldProgressList: [],
      budgetId: "",
      userList: [],
      carList: [],
      deviceList: [],
      participates: [],
      chooseCar: [],
      chooseDriver: [],
    };
  },
  watch: {
    taskName(newval, oldval) {
      if (newval == "项目生产") {
        // this.doesItExistBudget(this.taskForm.formId);
      }
    },
  },
  created() {
    if (this.taskName != "项目登记") {
      // this.doesItExistBudget(this.taskForm.formId);
      this.initProgress();
      this.getCarList();
      this.getDeviceList();
    }
  },
  mounted() {
  },
  methods: {
    initProgress() {
      getProject(this.taskForm.formId).then(res => {
        if (res.data) {
          this.form.entryTime = res.data.entryTime;
          this.form.exitTime = res.data.exitTime;
          if (res.data.participates) {
            this.participates = (res.data.participates.split(',')).map(Number);
          }
          if (res.data.cars) {
            this.form.cars = (res.data.cars.split(',')).map(Number);
          }
          if (res.data.drivers) {
            this.form.drivers = (res.data.drivers.split(',')).map(Number);
          }
          if (res.data.devices) {
            this.form.devices = (res.data.devices.split(',')).map(Number);
          }
          if (!(res.data.cars && res.data.drivers && res.data.devices)) {
            this.getCarAndDriver();
          }
        }
      });
      getProjectProgress(this.taskForm.formId).then(res => {
        if (res.data) {
          this.oldProgressList = res.data
          if (res.data != 0) {
            this.progressList = res.data;
          }
        }
      });
    },
    getChooseUser(val) {
      this.participates = val.map(item => item.userId);
      this.openPeople = false;
    },
    getChooseCar(val) {
      this.chooseCar = val;
      this.openCar = false;
    },
    getChooseDriver(val) {
      this.chooseDriver = val;
      this.openDriver = false;
    },
    // 通过用车审批表获取车辆和驾驶员信息
    getCarAndDriver() {
      listCarApproval({ projectId: this.taskForm.formId }).then(res => {
        if (res.rows) {
          this.form.drivers = []
          this.form.cars = []
          for (let data of res.rows) {
            if (data.cars) {
              let cars = data.cars.split(',');
              cars = cars.map(Number);
              cars.map(item => {
                this.form.cars.push(Number(item));
              });
            }
            if (data.drivers) {
              let drivers = data.drivers.split(',');
              drivers.map(item => {
                this.form.drivers.push(Number(item));
              });
            }
          }
        }
      })
      listDeviceApproval({ projectId: this.taskForm.formId }).then(res => {
        if (res.rows) {
          this.form.devices = []
          for (let data of res.rows) {
            if (data.devices) {
              let devices = data.devices.split(',');
              devices = devices.map(Number);
              devices.map(item => {
                this.form.devices.push(Number(item));
              });
            }
          }
        }
      })
    },
    addProgressList() {
      this.progressList.push({
        date: "",
        percentage: "",
        situation: "",
      });
    },
    deleProgressItem(index) {
      let arr = this.progressList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
    },
    handleAddProgress(form) {
      addProjectProgress(form);
    },
    // 暂存数据
    preserve() {
      // if (this.oldProgressList.length != 0) {
      //   delProjectProgress([this.taskForm.formId]).then(res => {
      //     for (let progress of this.progressList) {
      //       progress.projectId = this.taskForm.formId;
      //       addProjectProgress(progress);
      //     }
      //   });
      // } else {
      //   delProjectProgress([this.taskForm.formId]).then(res => {
      //     for (let progress of this.progressList) {
      //       progress.projectId = this.taskForm.formId;
      //       addProjectProgress(progress);
      //     }
      //   })
      // }
      delProjectProgress([this.taskForm.formId]).then(res => {
        for (let progress of this.progressList) {
          progress.projectId = this.taskForm.formId;
          addProjectProgress(progress);
        }
      })
      this.updateActualWorkList();
      this.form.projectId = this.taskForm.formId;
      this.form.cars = this.form.cars.length != 0 ? this.form.cars.join(',') : null;
      this.form.drivers = this.form.drivers.length != 0 ? this.form.drivers.join(',') : null;
      this.form.devices = this.form.devices.length != 0 ? this.form.devices.join(',') : null;
      // this.participates = this.participates.map(item => item.userId)
      this.form.participates = this.participates.join(',')
      updateProject(this.form).then(res => {
        this.$message.success("保存成功");
        if (this.form.cars && this.form.cars.trim() !== '') {
          this.form.cars = (this.form.cars.split(',')).map(item => Number(item.trim()));
          // 使用 trim() 来移除每个元素前后的空格（如果有的话）  
        }
        if (this.form.drivers && this.form.drivers.trim() !== '') {
          this.form.drivers = (this.form.drivers.split(',')).map(item => Number(item.trim()));
        }
        if (this.form.devices && this.form.devices.trim() !== '') {
          this.form.devices = (this.form.devices.split(',')).map(item => Number(item.trim()));
        }
      });
    },
    updateActualWorkList() {
      const list = this.$refs.actualRef.workList;
      const projectId = this.taskForm.formId
      delProjectWorkload(projectId).then(async () => {
        if (list.length > 0) {
          for (let l of list) {
            l.projectId = projectId
            await addProjectWorkload(l)
          }
        }
      })
    },
    // 查询车辆列表
    getCarList() {
      listCar({ pageSize: 9999, pageNum: 1 }).then(res => {
        this.carList = res.rows
      })
    },
    getDeviceList() {
      listDevice({
        pageNum: 1,
        pageSize: 99999999,
        type: '仪器设备'
      }).then(res => {
        this.deviceList = res.rows
      })
    },
    submitNextFlow() {
      this.$confirm('项目结束后不可再修改，请问是否确定结束？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.isFinished = '1'
        this.preserve();
        const params = { taskId: this.taskForm.taskId };// 获取下一个流程节点
        getNextFlowNode(params).then(res => {
          getProject(this.taskForm.formId).then(res => {
            if (res.data) {
              this.$set(this.taskForm.variables, "formId", this.taskForm.formId);
              this.$set(this.taskForm.variables, "archiveInitiator", res.data.projectLeader);
              this.$set(this.taskForm.variables, "settleInitiator", res.data.projectLeader);
              complete(this.taskForm).then(response => {
                this.$modal.msgSuccess(response.msg);
                this.$emit('goBack');
              });
            }
          })
        })
      }).catch(() => { });

    },
  },
};
</script>

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

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

.headers {
  position: relative;
  font-weight: bold;
  font-size: 18px;
  padding-left: 40px;
  padding-bottom: 40px;

  .line {
    position: absolute;
    left: 22px;
    top: 5px;
    width: 5px;
    height: 14px;
    border-radius: 10px;
    background-color: #2893e5;
  }
}

.title {
  background-color: #f5f7fa;
}

.delete-btn {
  color: #F56C6C;
  cursor: pointer;

  i {
    font-size: 25px;
  }
}

::v-deep .el-textarea.is-disabled .el-textarea__inner {
  color: #121212 !important;
}
</style>
