<!--
 * @Author: ysh
 * @Date: 2025-08-18 10:59:25
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-08-19 16:33:56
-->
<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="isFlow ? 18 : 24" :xs="24">
        <h2 style="text-align: center;">调岗申请表</h2>
        <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 :model="form" :rules="formRules" ref="form" label-width="175px" :disabled="taskName == ''"
          class="mt20">
          <el-divider></el-divider>
            <!-- 申请人 -->
            <el-row :gutter="20" >
                <el-col :md="12" :span="24">
                    <el-form-item label="申请人：" prop="applier" >
                        <span>{{ getUserName(form.applier) }}</span>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :span="24">
                    <el-form-item label="申请时间" prop="applyDate">
                        <el-date-picker style="width:140px;" v-model="form.applyDate" value-format="yyyy-MM-dd" type="date"
                    placeholder="选择日期" disabled>
                    </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 调整前所在部门及岗位 -->
            <el-row :gutter="20" >
                <el-col :md="12" :span="24">
                    <el-form-item label="调整前所在部门：" prop="beforeDeptId" :disabled="taskName != '调岗申请'">
                    {{ getDeptName(form.beforeDeptId) }}
                    </el-form-item>
                </el-col>
                <el-col :md="12" :span="24">
                    <el-form-item label="拟调整岗位：" prop="postList" >
                    <el-select v-model="postList.beforePostList" placeholder="请选择岗位" style="width:100%;" multiple :disabled="taskName != '调岗申请'" @change="$forceUpdate()">
                        <el-option v-for="item in beforepostOptions" :key="item.postId" :label="item.postName" :value="item.postId">
                        </el-option>
                    </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 调整后所在部门及岗位： -->
            <el-row :gutter="20" :disabled="taskName != '调岗申请'">
                <el-col :md="12" :span="24">
                    <el-form-item label="调整后所在部门：" prop="afterDeptId">
                        <el-select v-model="form.afterDeptId"  placeholder="请选择部门" :disabled="taskName != '调岗申请'">
                            <el-option v-for="item in this.$store.state.user.deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :span="24">
                    <el-form-item label="调整后岗位：" prop="postList">
                    <el-select v-model="postList.afterPostList" placeholder="请选择岗位" style="width:100%;" multiple :disabled="taskName != '调岗申请'" @change="$forceUpdate()">
                        <el-option v-for="item in allpostOptions" :key="item.postId" :label="item.postName" :value="item.postId">
                        </el-option>
                    </el-select>
                    </el-form-item>
                </el-col>
             </el-row>

            <el-divider></el-divider>

          <!-- 调整前所在部门意见 -->
            <el-form-item label="调整前所在部门意见：" prop="beforeDeptComment" label-width="160px">
                <el-input type="textarea" v-model="form.beforeDeptComment" :autosize="{ minRows: 4 }"
                :disabled="taskName != '调前部门审批'"></el-input>
                <auditor-row ref="beforeRef" :isCurrent="taskName == '调前部门审批'"
                :signature="form.beforeDeptLeader ? form.beforeDeptLeader : null" :signTime="form.beforeDeptTime"></auditor-row>
            </el-form-item>
            <!-- 调整后所在部门意见 -->
            <el-form-item label="调整后所在部门意见：" prop="afterDeptComment" label-width="160px">
                <el-input type="textarea" v-model="form.afterDeptComment" :autosize="{ minRows: 4 }"
                :disabled="taskName != '调后部门审批'"></el-input>
                <auditor-row ref="afterRef" :isCurrent="taskName == '调后部门审批'"
                :signature="form.afterDeptLeader ? form.afterDeptLeader : null" :signTime="form.afterDeptTime"></auditor-row>
            </el-form-item>
            <!-- 综合事务部意见： -->
            <el-form-item label="综合事务部意见：" prop="zhComment" label-width="160px">
                <el-input type="textarea" v-model="form.zhComment" :autosize="{ minRows: 4 }"
                :disabled="taskName != '综合事务部审批'"></el-input>
                <auditor-row ref="zhRef" :isCurrent="taskName == '综合事务部审批'"
                :signature="form.zhUserId ? form.zhUserId : null" :signTime="form.zhTime"></auditor-row>
            </el-form-item>
            <!-- 分管审核意见： -->
            <el-form-item label="分管审核意见：" prop="managerComment" label-width="160px">
                <el-input type="textarea" v-model="form.managerComment" :autosize="{ minRows: 4 }"
                :disabled="taskName != '分管审批'"></el-input>
                <auditor-row ref="fgRef" :isCurrent="taskName == '分管审批'"
                :signature="form.managerUserId ? form.managerUserId : null" :signTime="form.managerTime"></auditor-row>
            </el-form-item>
            <!-- 总经理审批意见： -->
            <el-form-item label="总经理意见：" prop="zjlComment" label-width="160px">
                <el-input type="textarea" v-model="form.zjlComment" :autosize="{ minRows: 4 }"
                :disabled="taskName != '总经理审批'"></el-input>
                <auditor-row ref="zjlRef" :isCurrent="taskName == '总经理审批'"
                :signature="form.zjlUserId ? form.zjlUserId : null" :signTime="form.zjlTime"></auditor-row>
            </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <div style="text-align: center;" v-if="taskName" class="mt30">
          <el-button type="danger" @click="returnOpen = true" v-if="taskName != '调岗申请'">退回</el-button>
          <el-button type="primary" @click="submitForm">{{ taskName != '总经理审批' ? '提交下一个流程' : '批准' }}</el-button>
        </div>
      </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="returnOpen" width="40%" append-to-body>
      <return-btn :taskForm="taskForm" :comment="commentByRole()" @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 { listTransfer, getTransfer, delTransfer, addTransfer, updateTransfer } from "@/api/oa/transfer/transfer";
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import { allocatedUserList } from "@/api/system/role";
import ReturnComment from "@/views/flowable/form/components/flowBtn/returnComment.vue";
import ReturnBtn from "@/views/flowable/form/components/flowBtn/returnBtn.vue";
import { getUser, updateUser } from "@/api/system/user";
import { getUsersDeptLeaderByDept, getUsersManageLeaderByDept, getUserByPost } from '@/api/system/post';
import AuditorRow from '@/views/flowable/form/components/auditorRow.vue';
export default {
  components: {
    flow,
    ReturnComment,
    ReturnBtn,
    AuditorRow
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    isFlow: {
      type: Boolean,
      default: true
    }
  },
  created() {
    if (this.isFlow)
      flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
        this.flowData = res.data;
      })
    // 初始化表单数据
    this.initFormData(),
    this.getPostbyUserId()
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      flowData: {},
      isEdit: false,
      // 调整前岗位选项
      beforepostOptions: [],
      // 所有岗位选项
      allpostOptions: [],
      // 岗位
      posts: [],
      postList:{
        beforePostList: [],
        afterPostList: [],
      },
      form: {
        dept: {
          deptName: '',
        },
        transferId: null,
        applier: null,
        applyDate: null,
        beforeDeptId: null,
        beforePostId: null,
        afterDeptId: null,
        afterPostId: null,
        beforeDeptComment: null,
        beforeDeptLeader: null,
        beforeDeptTime: null,
        afterDeptComment: null,
        afterDeptTime: null,
        afterDeptLeader: null,
        zhComment: null,
        zhTime: null,
        zhUserId: null,
        managerComment: null,
        managerTime: null,
        managerUserId: null,
        zjlComment: null,
        zjlTime: null,
        zjlUserId: null
      },
      rules: {},
      returnOpen: false,
      showAlter: true
    }
  },
  computed: {
    // 动态生成验证规则
    formRules() {
      if (this.taskName == '') {
        return {}; // 当taskName为空时，不进行验证
     }else if(this.taskName == '调岗申请'){
        return {
          beforePostList: [
            { required: true, message: '请选择调整前岗位', trigger: 'change', type: 'array'  }
          ],
          afterDeptId: [
            { required: true, message: '请选择调整后部门', trigger: 'change' }
          ],
          afterPostList: [
            { required: true, message: '请选择调整后岗位', trigger: 'change', type: 'array' }
          ]
     }}else if(this.taskName=='调前部门审批'){
        return{
          beforeDeptComment: [
            { required: true, message: '请填写审批意见', trigger: 'blur'}
          ]
     }}else if(this.taskName=='调后部门审批'){
        return{
          afterDeptComment: [
            { required: true, message: '请填写审批意见', trigger: 'blur' }
          ]
     }}else if(this.taskName=='综合事务部审批'){
        return{
          zhComment: [
            { required: true, message: '请填写审批意见', trigger: 'blur' }
          ]
     }}else if(this.taskName=='分管审批'){
        return{
          managerComment: [
            { required: true, message: '请填写审批意见', trigger: 'blur' }
          ]
     }}else if(this.taskName=='总经理审批'){
        return{
          zjlComment: [
            { required: true, message: '请填写审批意见', trigger: 'blur' }
          ]
     }}
    }
  },
  methods: {
    // 初始化表单数据
    initFormData() {
      getTransfer(this.taskForm.formId).then(res => {
        if (res.data) {
          this.form = res.data;
          this.isEdit = true;
          this.postList.beforePostList = this.form.beforePostId.split(',').map(item => item.trim())
                                    .filter(item => item !== '') .map(item => Number(item)).filter(num => !isNaN(num)); 
          this.postList.afterPostList = this.form.afterPostId.split(',').map(item => item.trim())
                                    .filter(item => item !== '') .map(item => Number(item)).filter(num => !isNaN(num));
        } else {
          this.form.applier = this.$store.state.user.id;
          this.form.applyDate = this.parseTime(new Date(), '{y}-{m}-{d}');
          this.form.dept.deptName = this.$store.getters.deptName;
          this.form.beforeDeptId=this.$store.getters.deptId;
        }
      })
    },
    // 保存
    async saveDraft() {
      if (this.taskName == '') {
        this.$message.info('当前为只读模式，无法保存')
        return;
      }
      if (this.taskName == '调岗申请') {
        this.form.beforePostId = this.postList.beforePostList.join(',');
        this.form.afterPostId = this.postList.afterPostList.join(',');
      }else if (this.taskName == '调前部门审批') {
        this.form.beforeDeptLeader = this.$refs.beforeRef.localSignatureUserId;
        this.form.beforeDeptTime = this.$refs.beforeRef.loaclSignTime;
      } else if (this.taskName == '调后部门审批') {
        this.form.afterDeptLeader = this.$refs.afterRef.localSignatureUserId;
        this.form.afterDeptTime = this.$refs.afterRef.loaclSignTime;
      } else if (this.taskName == '综合事务部审批') {
        this.form.zhUserId = this.$refs.zhRef.localSignatureUserId;
        this.form.zhTime = this.$refs.zhRef.loaclSignTime;
      } else if (this.taskName == '分管审批') {
        this.form.managerUserId = this.$refs.fgRef.localSignatureUserId;
        this.form.managerTime = this.$refs.fgRef.loaclSignTime;
      } else if (this.taskName == '总经理审批') {
        this.form.zjlUserId = this.$refs.zjlRef.localSignatureUserId;
        this.form.zjlTime = this.$refs.zjlRef.loaclSignTime;
      }

      if (this.isEdit) {
        await updateTransfer(this.form);
      } else {
        this.form.transferId = this.taskForm.formId;
        await addTransfer(this.form);
        this.isEdit = true;
      }
      this.$message.success('保存成功')
    },
    // 提交表单
    submitForm() {
      if (this.taskName == '') {
        this.$message.info('当前为只读模式，无法提交')
        return;
      }

      this.$refs.form.validate((valid) => {
        if (valid) {
          let msg = '确认提交调岗申请表？';
          if (this.taskName == '总经理审批') {
            msg = '最后一个节点，提交将无法修改，是否确认提交？';
          }
          this.$confirm(msg, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.submitFlow()
          }).catch(() => {
            this.$message.info('已取消提交')
          })
        } else {
          this.$message.error('请完善表单信息')
          return false
        }
      })
    },
    async submitFlow() {
      await this.saveDraft();
      
      if (this.taskName == '调岗申请') {  
        const res = await getUsersDeptLeaderByDept({ deptId: this.form.beforeDeptId });
        this.$set(this.taskForm.variables, "approval", res.data.userId);
      } else if (this.taskName == '调前部门审批') {
        const res = await getUsersDeptLeaderByDept({ deptId: this.form.afterDeptId });
        this.$set(this.taskForm.variables, "approval", res.data.userId);
      } else if (this.taskName == '调后部门审批') {
        const res = await getUsersDeptLeaderByDept({ deptId: 104 });
        this.$set(this.taskForm.variables, "approval", res.data.userId);
      } else if (this.taskName == '综合事务部审批') {
        let managerList = []
        let result = await getUsersManageLeaderByDept({ deptId: this.form.afterDeptId });
        result.data.forEach(element => {managerList.push(element.userId)});
        this.$set(this.taskForm.variables, "approvalList", managerList);
      } else if (this.taskName == '分管审批') {
        const res = await getUserByPost({ postName: "总经理" });
        this.$set(this.taskForm.variables, "approval", res.data[0].userId);
      }else if(this.taskName=='总经理审批'){
        this.updateUserDeptAndPost();
      }

      await getNextFlowNode({ taskId: this.taskForm.taskId });
      const response = await complete(this.taskForm);
      this.$modal.msgSuccess(response.msg);
      this.$emit('goBack');
    },

    //获取职位
    getPostbyUserId() {
      if(this.taskName=="调岗申请"){
        getUser(this.$store.state.user.id).then(response => {
          this.allpostOptions = response.posts;
          for (let p of response.posts) {
            for (let ids of response.postIds) {
              if (p.postId == ids) {
                this.beforepostOptions.push(p);
              }
            }
          }
        });
      }else{
        getUser(this.$store.state.user.id).then(response => {
          this.allpostOptions = response.posts;
          this.beforepostOptions = response.posts;
        });
      }
    },
    //转换岗位id格式
    postIdConvert(val){
      // 处理空值
      if (val === null || val === undefined || val === '') {
        return '';
      }
      if (Array.isArray(val)) {
        return val.map(num => String(num)).join(',');
      }
      if (typeof val === 'string') {
        return val.split(',')
          .map(item => item.trim())
          .filter(item => item !== '')
          .map(item => Number(item))
          .filter(num => !isNaN(num));
      }
      return '';
    },
    //更新用户部门和岗位
    async updateUserDeptAndPost(){
      const userinfo = await getUser(Number(this.form.applier));
      userinfo.data.deptId = this.form.afterDeptId;
      userinfo.data.roleIds = userinfo.roleIds;
      userinfo.data.postIds = this.form.afterPostId.split(',').map(item => Number(item.trim())).filter(num => !isNaN(num));
      updateUser(userinfo.data).then(response => {
       this.$modal.msgSuccess("修改成功");
      });
    },
    isReturn(val) {
      this.showAlter = val;
    },
    commentByRole() {
      if (this.taskName == '调前部门审批') {
        return this.form.beforeDeptComment
      } else if (this.taskName == '调后部门审批') {
        return this.form.afterDeptComment
      } else if (this.taskName == '综合事务部审批') {
        return this.form.zhComment
      } else if (this.taskName == '分管审批') {
        return this.form.managerComment
      } else if (this.taskName == '总经理审批') {
        return this.form.zjlComment
      } 
    },
  }
}
</script>

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

.process-steps {
  margin: 20px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.current-step-info {
  margin: 20px 0;

  .step-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    i {
      color: #409eff;
      margin-right: 8px;
      font-size: 16px;
    }

    .step-title {
      font-weight: bold;
      color: #303133;
      font-size: 16px;
    }
  }

  .step-description {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
  }
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;

  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 2px solid #409eff;

    i {
      color: #409eff;
      margin-right: 8px;
      font-size: 18px;
    }

    svg {
      color: #409eff;
      margin-right: 8px;
      font-size: 18px;
    }

    span {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
    }
  }
}

.sign {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-right: 80px;
  line-height: 30px;
  /* 如果需要垂直居中 */
}

.mt20 {
  margin-top: 20px;
}

.mt30 {
  margin-top: 30px;
}

.mb20 {
  margin-bottom: 20px;
}

.ml20 {
  margin-left: 20px;
}

.mr20 {
  margin-right: 20px;
}

.mt10 {
  margin-top: 10px;
}
</style>