<template>
  <div class="study-form">
    <el-row :gutter="20">
      <el-col :span="flowDisabled ? 18 : 24" :xs="24">
        <div class="form-title">参培审核表</div>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="上报人" prop="user.nickName">
                {{ getUserName(form.userId) }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="上报人部门" prop="dept.deptName">
                {{ getDeptName(form.deptId) }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="上报日期" prop="reportTime">
                {{ form.reportTime }}
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="培训名称" prop="trainName">
                <el-input v-model="form.trainName" placeholder="请输入培训名称" :disabled="taskName != '参培上报'" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="参培日期" prop="trainTime">
            <el-date-picker clearable v-model="form.trainTime" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择参培日期" :disabled="taskName != '参培上报'">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="主要内容" prop="content">
            <el-input v-model="form.content" type="textarea" :rows="4" placeholder="请输入主要内容"
              :disabled="taskName != '参培上报'" />
          </el-form-item>

          <el-form-item label="佐证附件" prop="document">
            <FileUpload v-if="form.document == null || form.document == ''" :disabled="taskName != '参培上报'"
              :isShowTip="false" :limit="1" :filePathName="'参培/佐证附件'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getDocumentPath"></FileUpload>
            <div v-if="form.document">
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.document}`)">
                {{ getFileName(form.document) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.document}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
              <el-link class="ml20" type="danger" @click="handleDeleteDocument" v-if="taskName == '参培上报'"
                :underline="false">
                <span class="el-icon-delete">删除文件</span>
              </el-link>
              <FileUpload v-if="taskName == '参培申请'" :limit="1" :filePathName="'参培/佐证附件'"
                :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getDocumentPath"></FileUpload>
            </div>
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学时" prop="hours">
                <el-input-number v-model="form.hours" :min="0" :precision="1" :disabled="taskName != '参培上报'" />
              </el-form-item>
            </el-col>
          </el-row>

          <template v-if="taskName != '参培上报'">
            <el-form-item label="部门审核意见" prop="dept_comment">
              <el-input v-model="form.deptComment" type="textarea" :rows="3" placeholder="请输入部门审核意见"
                :disabled="taskName != '部门审核'" />
            </el-form-item>

            <el-row>
              <el-col :span="6" :offset="12" :xs="24">
                <el-form-item label="签名：" label-width="120px">
                  <span class="auditor"> {{ getUserName(form.deptUserId) }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px">
                  <span> {{ form.deptTime ? form.deptTime : deptTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </el-form>
        <div style="text-align: center;" v-if="taskName != ''">
          <el-button type="warning" @click="saves">保 存</el-button>
          <el-button type="primary" @click="submit">提 交</el-button>
        </div>
      </el-col>
      <el-col :span="6" :xs="24" v-if="flowDisabled">
        <el-card>
          <h2 style="text-align: center;">流程进度</h2>
          <div>
            <flow :flowData="flowData" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import flow from '@/views/flowable/task/todo/detail/flow'
import { flowXmlAndNode } from "@/api/flowable/definition";
import { parseTime } from "@/utils/ruoyi";
import { getTrainApproval, updateTrainApproval, addTrainApproval } from "@/api/oa/study/trainApproval";
import { getUsersDeptLeader, getUsersDeptLeaderByDept, getUsersViceDeptLeaderByDept, getUsersManageLeaderByDept } from '@/api/system/post.js'
import { complete, getNextFlowNode } from "@/api/flowable/todo";

export default {
  name: 'StudyForm',
  components: {
    flow,
  },
  props: {
    taskForm: {
      type: Object,
      required: true
    },
    flowDisabled: {
      type: Boolean,
      default: true
    },
    taskName: {
      type: String,
      required: true
    }
  },
  watch: {
    'taskForm.formId'() {
      this.initForm();
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      form: {
        participateId: '',
        userId: '',
        deptId: '',
        reportTime: '',
        trainTime: '',
        trainName: '',
        content: '',
        document: '',
        hours: 0,
        dept_user_id: '',
        dept_time: '',
        dept_comment: '',
        user: {
          nickName: '',
        },
        dept: {
          deptName: '',
        },
        applierUser: null
      },
      rules: {
        trainTime: [
          { required: true, message: '请选择参培日期', trigger: 'change' }
        ],
        trainName: [
          { required: true, message: '请输入培训名称', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入主要内容', trigger: 'blur' }
        ],
        hours: [
          { required: true, message: '请输入学时', trigger: 'blur' }
        ]
      },
      flowData: {},
      deptUser: '',
      deptTime: undefined,
      formTotal: 0,
    }
  },
  created() {
    if (this.flowDisabled) {
      flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
        this.flowData = res.data;
      })
    }
    this.form.user.nickName = this.$store.getters.name;
    this.form.dept.deptName = this.$store.getters.deptName;
    this.form.userId = this.$store.getters.userId;
    this.form.deptId = this.$store.getters.deptId;
    this.form.reportTime = parseTime(new Date(), '{y}-{m}-{d}');
    if (this.taskForm && this.taskForm.formId) {
      this.form.participateId = this.taskForm.formId;
    }
    this.initForm();
  },
  methods: {
    initForm() {
      getTrainApproval(this.taskForm.formId).then(res => {
        if (res.data) {
          this.formTotal = 1;
          this.form = res.data;
          if (this.taskName == '部门审核') {
            this.form.deptUserId = this.$store.getters.userId;
            this.form.deptTime = parseTime(new Date(), '{y}-{m}-{d}')
          }
        } else {
          this.formTotal = 0;
        }
      })
    },
    getDocumentPath(val) {
      let arr = val.split('/upload')
      this.form.document = arr[1]
      if (val == "") {
        this.form.document = ""
      }
    },
    getFileName(val) {
      if (val) {
        return val.substring(val.lastIndexOf('/') + 1)
      }
      return ''
    },
    handleDeleteDocument() {
      this.$modal.confirm('是否确认删除该附件？').then(() => {
        this.form.document = '';
      }).catch(() => { });
    },
    saves() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 更新参培审批表
          if (this.formTotal) {
            updateTrainApproval(this.form).then(() => {
              this.$modal.msgSuccess("保存成功");
            });
          } else {
            addTrainApproval(this.form).then(() => {
              this.$modal.msgSuccess("保存成功");
              this.formTotal = 1;
            });
          }
        }
      });
    },
    submit() {
      this.$modal.confirm('是否提交流程？').then(() => {
        this.submitForm();
      }).catch(() => { });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.taskName == '部门审核') {
            this.form.dept_user_id = this.$store.getters.userId;
            this.form.dept_time = parseTime(new Date(), '{y}-{m}-{d}')
          }
          // 更新参培审批表
          if (this.formTotal) {
            updateTrainApproval(this.form).then(() => {
              // 获取下一步流程
              this.getNextFlowFn();
            });
          } else {
            addTrainApproval(this.form).then(() => {
              // 获取下一步流程
              this.getNextFlowFn();
            });
          }
        }
      });
    },
    getNextFlowFn() {
      getNextFlowNode({ taskId: this.taskForm.taskId }).then(() => {
        if (this.taskName == '参培上报') {
          getUsersDeptLeader({ userId: this.$store.getters.userId }).then(res => {
            let userId = res.data.userId;
            this.$set(this.taskForm.variables, "approval", userId);
            this.handleComplete(this.taskForm);
          })
        } else {
          this.handleComplete(this.taskForm);
        }
      });
    },
    handleComplete(taskForm) {
      complete(taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.$emit('goBack');
      })
    }
  }
}
</script>

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

.study-form {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .form-title {
    font-size: 20px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30px;
    color: #303133;
  }

  .el-form {
    max-width: 1200px;
    margin: 0 auto;
  }

  .el-divider {
    margin: 24px 0;
  }

  .upload-demo {
    .el-upload {
      width: 100%;
    }
  }
}
</style>