<template>
  <div class="task-formulate">
    <div class="operation-bar">
      <span>预定的监审工作起止时间：</span>
      <el-date-picker
        v-model="formData.workflow.plannedAuditStartDate"
        type="date"
        placeholder="开始日期"
        style="width: 150px; margin: 0 10px"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        disabled
      ></el-date-picker>
      <span>至</span>
      <el-date-picker
        v-model="formData.workflow.plannedAuditEndDate"
        type="date"
        placeholder="结束日期"
        style="width: 150px; margin: 0 10px"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        disabled
      ></el-date-picker>
    </div>
    <!-- <div class="operation-bar">
      <el-button
        type="success"
        plain
        icon="el-icon-circle-plus"
        :disabled="isView"
        @click="handleSetWorkflow"
      >
        工作环节设置
      </el-button>
    </div> -->
    <CostAuditTable
      :table-data="actualWorkflowData.list"
      :columns="actualWorkflowData.listColumns"
      :show-index="true"
      :show-action-column="false"
    ></CostAuditTable>
    <div class="table-description">
      说明：为所有内部环节预置办理人员、流转操作按钮、环节截止时间；环节时限不能超过预定的工作流程起止时间。
    </div>
    <el-dialog
      title="工作环节设置"
      :visible.sync="dialogs.setStepDialogVisible"
      width="70%"
    >
      <div class="operation-bar">
        <span>请选择预定的监审工作起止时间：</span>
        <el-date-picker
          v-model="formData.workflow.plannedAuditStartDate"
          type="date"
          placeholder="开始日期"
          style="width: 150px; margin: 0 10px"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
        <span>至</span>
        <el-date-picker
          v-model="formData.workflow.plannedAuditEndDate"
          type="date"
          placeholder="结束日期"
          style="width: 150px; margin: 0 10px"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </div>
      <CostAuditTable
        :table-data="actualWorkflowData.stepList"
        :columns="actualWorkflowData.workflowColumns"
        :show-index="true"
        :show-pagination="true"
        :show-action-column="true"
        :table-props="{
          maxHeight: '500',
        }"
        :pagination="actualWorkflowData.pagination"
        @pagination-change="handlePaginationChange"
      >
        <template #mainUserId="{ row }">
          <el-select
            v-if="row.nodeType == 1"
            v-model="row.mainUserId"
            filterable
            allow-create
            default-first-option
            placeholder="请选择主办人员"
            style="width: 100%"
          >
            <el-option
              v-for="item in formatterMainUserList()"
              :key="item.userId"
              :label="item.fullname"
              :value="item.userId"
            />
          </el-select>
        </template>
        <template #userId="{ row }">
          <el-select
            v-if="row.nodeType == 1"
            v-model="row.userId"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择从办人员"
            style="width: 100%"
            :disabled="!row.mainUserId"
          >
            <el-option
              v-for="item in formatterUserList(row.mainUserId)"
              :key="item.userId"
              :label="item.fullname"
              :value="item.userId"
            />
          </el-select>
        </template>
        <template #status="{ row }">
          <el-select
            v-if="row.nodeType == 1"
            v-model="row.status"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择预置流转操作"
            style="width: 100%"
          >
            <el-option
              v-for="item in dictData['processStatus']"
              :key="item.key"
              :label="item.name"
              :value="item.key"
            />
          </el-select>
        </template>
        <template #endTime="{ row }">
          <el-date-picker
            v-model="row.endTime"
            type="date"
            placeholder="请选择截止时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
            :picker-options="getPickerOptions(row)"
          ></el-date-picker>
        </template>
      </CostAuditTable>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading.saveStep"
          @click="handleSaveSetStep"
        >
          确认
        </el-button>
        <el-button @click="dialogs.setStepDialogVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>
    <!-- 设置流程环节弹窗 -->
    <el-dialog
      v-loading="loading.save"
      title="设置流程环节"
      :visible.sync="dialogs.stepDialogVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="currentStepForm"
        :model="formData.currentStep"
        label-width="120px"
        :rules="formData.currentStepRules"
      >
        <el-form-item label="流程环节：" prop="processNodeValue">
          <el-input
            v-model="formData.currentStep.processNodeValue"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="主办人员：" prop="mainUserId">
          <el-select
            v-model="formData.currentStep.mainUserId"
            filterable
            allow-create
            default-first-option
            placeholder="请选择主办人员"
            style="width: 100%"
            :disabled="formData.currentStep.nodeType == 0"
          >
            <el-option
              v-for="item in formatterMainUserList()"
              :key="item.userId"
              :label="item.fullname"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="从办人员：" prop="userId">
          <el-select
            v-model="formData.currentStep.userId"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择从办人员"
            style="width: 100%"
            :disabled="
              !formData.currentStep.mainUserId ||
              formData.currentStep.nodeType == 0
            "
          >
            <el-option
              v-for="item in formatterUserList(formData.currentStep.mainUserId)"
              :key="item.userId"
              :label="item.fullname"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预置流转操作：" prop="status">
          <el-select
            v-model="formData.currentStep.status"
            filterable
            multiple
            allow-create
            default-first-option
            placeholder="请选择预置流转操作"
            style="width: 100%"
            :disabled="formData.currentStep.nodeType == 0"
          >
            <el-option
              v-for="item in dictData['processStatus']"
              :key="item.key"
              :label="item.name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="截止时间：" prop="endTime">
          <el-date-picker
            v-model="formData.currentStep.endTime"
            type="date"
            placeholder="请选择截止时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
            :disabled="isTimePickerDisabled"
            :picker-options="getPickerOptions(formData.currentStep)"
          ></el-date-picker>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading.save"
          @click="handleSaveStep('currentStepForm', 'list')"
        >
          确认
        </el-button>
        <el-button @click="dialogs.stepDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { taskMixin } from '@/views/costAudit/projectInfo/auditTaskManage/taskCustomizedRelease/index.js'
  import {
    getCostProjectNodeTmpletePageList,
    saveProcess,
  } from '@/api/taskCustomizedRelease.js'
  import CostAuditTable from '@/components/costAudit/CostAuditTable.vue'
  export default {
    components: { CostAuditTable },
    mixins: [taskMixin],
    props: {
      project: {
        type: Object,
        default: () => {},
      },
      isView: {
        type: Boolean,
        default: false,
      },
      workflowData: {
        type: Object,
        default: () => {},
      },
    },
    data() {
      return {
        formData: {
          currentStepRules: {
            endTime: [
              { required: true, message: '请选择截止时间', trigger: 'change' },
              {
                validator: (rule, value, callback) => {
                  if (
                    !this.formData.workflow.plannedAuditStartDate ||
                    !this.formData.workflow.plannedAuditEndDate
                  ) {
                    return callback()
                  }
                  if (value < this.formData.workflow.plannedAuditStartDate) {
                    return callback(new Error('截止时间不能早于工作开始时间'))
                  }
                  if (value > this.formData.workflow.plannedAuditEndDate) {
                    return callback(new Error('截止时间不能晚于工作结束时间'))
                  }
                  callback()
                },
                trigger: 'change',
              },
            ],
          },
        },
        // 内部工作流数据，避免直接修改 prop
        localWorkflowData: {
          list: [],
          stepList: [],
          pagination: {
            currentPage: 1,
            pageSize: 10,
            total: 0,
          },
        },
      }
    },
    computed: {
      // 合并外部 workflowData 和内部数据
      actualWorkflowData() {
        return {
          ...this.workflowData,
          list:
            this.localWorkflowData.list.length > 0
              ? this.localWorkflowData.list
              : this.workflowData.list || [],
          stepList:
            this.localWorkflowData.stepList.length > 0
              ? this.localWorkflowData.stepList
              : this.workflowData.stepList || [],
          pagination: {
            ...(this.workflowData.pagination || {}),
            ...this.localWorkflowData.pagination,
          },
        }
      },
      isTimePickerDisabled() {
        if (
          !this.formData.currentStep ||
          !this.formData.currentStep.processNodeKey
        ) {
          return false
        }
        const stepList =
          this.actualWorkflowData.list.length > 0
            ? this.actualWorkflowData.list
            : this.actualWorkflowData.stepList
        if (!stepList || stepList.length <= 1) {
          return false
        }
        const currentIndex = stepList.findIndex(
          (item) =>
            item.processNodeKey === this.formData.currentStep.processNodeKey
        )
        if (currentIndex <= 0) {
          return false
        }
        const prevStep = stepList[currentIndex - 1]
        return !prevStep.endTime
      },
    },
    watch: {
      // 监听 workflowData prop 变化，同步到内部数据
      workflowData: {
        handler(newVal) {
          if (newVal) {
            this.localWorkflowData.list = newVal.list || []
            this.localWorkflowData.stepList = newVal.stepList || []
            if (newVal.pagination) {
              this.localWorkflowData.pagination = {
                ...this.localWorkflowData.pagination,
                ...newVal.pagination,
              }
            }
          }
        },
        deep: true,
        immediate: true,
      },
      'workflowData.stepList': {
        handler(newList) {
          if (newList && newList.length > 0) {
          }
        },
        deep: true,
      },
    },
    mounted() {
      this.getWorkflow()
    },
    methods: {
      formatterUserList(userId) {
        return this.formatterMainUserList().filter(
          (item) => item.userId !== userId
        )
      },
      formatterMainUserList() {
        if (!this.userList || !Array.isArray(this.userList)) {
          return []
        }
        if (
          !this.project ||
          !this.project.projectMembers ||
          typeof this.project.projectMembers !== 'string'
        ) {
          return this.userList
        }
        try {
          const projectMemberIds = this.project.projectMembers.split(',')
          const filteredUsers = this.userList.filter((item) =>
            projectMemberIds.includes(item.userId)
          )
          return filteredUsers
        } catch (error) {
          return this.userList
        }
      },
      getPickerOptions(row) {
        const stepList = this.actualWorkflowData.stepList
        const rowIndex = stepList.findIndex(
          (item) => item.processNodeKey === row.processNodeKey
        )
        let pickerOptions = {
          disabledDate: (time) => {
            const startLimit = this.formData.workflow.plannedAuditStartDate
              ? new Date(this.formData.workflow.plannedAuditStartDate).getTime()
              : null
            const endLimit = this.formData.workflow.plannedAuditEndDate
              ? new Date(this.formData.workflow.plannedAuditEndDate).getTime()
              : null
            if (startLimit && time.getTime() < startLimit - 8.64e7) {
              return true
            }
            if (endLimit && time.getTime() > endLimit) {
              return true
            }
            if (rowIndex > 0) {
              const prevStep = stepList[rowIndex - 1]
              if (prevStep && prevStep.endTime) {
                const prevEndTime = new Date(prevStep.endTime).getTime()
                if (time.getTime() <= prevEndTime - 8.64e7) {
                  return true
                }
              }
            }
            return false
          },
        }
        return pickerOptions
      },
      handleSetWorkflow() {
        this.getUser()
        this.dialogs.setStepDialogVisible = true
        if (this.actualWorkflowData.list.length > 0) {
          this.localWorkflowData.stepList = this.actualWorkflowData.list.map(
            (item) => ({
              ...item,
              userId: item.userId ? item.userId.split(',') : [],
              status: item.status ? item.status.split(',') : [],
            })
          )
          this.notifyWorkflowDataUpdate()
        } else {
          getCostProjectNodeTmpletePageList({
            pageNum: this.actualWorkflowData.pagination.currentPage,
            pageSize: this.actualWorkflowData.pagination.pageSize,
            processId: '1',
          }).then((res) => {
            this.localWorkflowData.stepList = res.value.records.map((item) => ({
              ...item,
              userId: item.userId ? item.userId.split(',') : [],
              status: item.status ? item.status.split(',') : [],
            }))
            this.localWorkflowData.pagination.total = res.value.total
            this.notifyWorkflowDataUpdate()
          })
        }
      },
      // 通知父组件更新 workflowData
      notifyWorkflowDataUpdate() {
        this.$emit('update:workflowData', { ...this.actualWorkflowData })
      },
      handleSetStep(row) {
        this.getUser()
        this.formData.currentStep = {
          ...row,
          userId: row.userId ? row.userId.split(',') : [],
          status: row.status ? row.status.split(',') : [],
        }
        this.dialogs.stepDialogVisible = true
        this.loading.save = false
        this.$nextTick(() => {
          if (this.$refs.currentStepForm) {
            this.$refs.currentStepForm.clearValidate()
          }
        })
      },
      handleSaveStep(formName, type) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (type == 'list') {
              this.localWorkflowData.list = this.actualWorkflowData.list.map(
                (item) => {
                  if (
                    item.processNodeKey ==
                    this.formData.currentStep.processNodeKey
                  ) {
                    return {
                      ...item,
                      ...this.formData.currentStep,
                      userId: this.formData.currentStep.userId.join(','),
                      status: this.formData.currentStep.status.join(','),
                    }
                  }
                  return item
                }
              )
              this.notifyWorkflowDataUpdate()
              this.handleSaveSetStep('list')
            }
          } else {
            return false
          }
        })
      },
      handleSaveSetStep(type) {
        if (!this.formData.workflow.plannedAuditStartDate) {
          this.$message.error('请选择预定的监审工作开始日期')
          return
        }
        if (!this.formData.workflow.plannedAuditEndDate) {
          this.$message.error('请选择预定的监审工作结束日期')
          return
        }
        let stepList =
          type === 'list'
            ? this.actualWorkflowData.list
            : this.actualWorkflowData.stepList
        if (stepList && stepList.length > 1) {
          const sortedSteps = [...stepList].sort((a, b) => {
            return stepList.indexOf(a) - stepList.indexOf(b)
          })
          for (let i = 1; i < sortedSteps.length; i++) {
            const currentStep = sortedSteps[i]
            const prevStep = sortedSteps[i - 1]
            if (currentStep.endTime && prevStep.endTime) {
              if (new Date(currentStep.endTime) <= new Date(prevStep.endTime)) {
                this.$message.error(
                  `第${i + 1}个环节的截止时间必须大于第${i}个环节的截止时间`
                )
                return
              }
            } else if (currentStep.endTime && !prevStep.endTime) {
              this.$message.error(`请先设置第${i}个环节的截止时间`)
              return
            } else if (!currentStep.endTime && prevStep.endTime) {
              this.$message.error(`请设置第${i + 1}个环节的截止时间`)
              return
            }
          }
        }
        this.loading.save = true
        let data = {
          nodeReqList: [
            {
              endTime: '',
              id: '',
              mainUserId: '',
              processNodeKey: '',
              status: '',
              userId: '',
            },
          ],
          plannedAuditEndDate: this.formData.workflow.plannedAuditEndDate,
          plannedAuditStartDate: this.formData.workflow.plannedAuditStartDate,
          processId: this.actualWorkflowData.detailInfo?.processId || '1',
          projectId: this.project.projectId,
        }
        if (type == 'list') {
          data.nodeReqList = this.actualWorkflowData.list
        } else {
          data.nodeReqList = this.actualWorkflowData.stepList.map((item) => {
            return {
              ...item,
              userId: item.userId.join(','),
              status: item.status.join(','),
            }
          })
        }
        saveProcess(data)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success('保存成功')
              this.loading.save = false
              if (type == 'list') {
                this.dialogs.stepDialogVisible = false
              } else {
                this.dialogs.setStepDialogVisible = false
              }
              this.getWorkflow()
            }
          })
          .catch(() => {
            this.loading.save = false
          })
      },
    },
  }
</script>

<style scoped lang="scss">
  @import '@/styles/costAudit.scss';
</style>
