<template>
  <div class="app-container" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
    <el-row :gutter="20">
      <el-col :span="18" :xs="24">
        <h2 class="text-center">借款申请</h2>
        <el-form ref="form" :model="form" :rules="rules" label-width="125px">
          <el-row :gutter="20">
            <el-col :span="6" :xs="24">
              <el-form-item label="申请人" prop="user.nickName">
                {{ form.applierUser ? form.applierUser.nickName : form.user.nickName }}
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="24">
              <el-form-item label="申请部门" prop="dept.deptName">
                {{ form.dept.deptName }}
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="24">
              <el-form-item label="申请时间" prop="date">
                <el-date-picker style="width:140px;" v-model="form.applyDate" value-format="yyyy-MM-dd" type="date"
                  placeholder="选择日期" :disabled="taskName != '借款申请'">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="借款类型" prop="borrowUsage" v-if="taskForm.procDefName == '借款审批'">
            <el-radio-group v-model="form.borrowUsage" @change="hanldeChangeType" :disabled="taskName != '借款申请'">
              <el-radio label="0">项目借款</el-radio>
              <el-radio label="1">非项目借款</el-radio>
              <el-radio label="2">工会借款</el-radio>
              <el-radio label="3">党委借款</el-radio>
              <el-radio label="4">团委借款</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="借款事由" prop="applyReason" v-if="taskForm.procDefName == '借款审批' && !isProject">
            <el-input v-model="form.applyReason" :disabled="taskName != '借款申请'"></el-input>
          </el-form-item>
          <el-form-item label="项目编号" prop="projectId" v-if="taskForm.procDefName == '借款审批' && isProject">
            <el-select v-model="form.projectId" filterable placeholder="请选择" @change="handleSelectProject"
              :disabled="taskName != '借款申请'" clearable>
              <el-option v-for="item in projectList" :key="item.value" :label="item.projectNumber"
                :value="item.projectId">
              </el-option>
            </el-select>
            <el-descriptions border v-if="isSelect" style="margin-top: 10px;" :column="1">
              <el-descriptions-item label="项目编号" label-class-name="my-label">{{ chooseProject.projectNumber
                }}</el-descriptions-item>
              <el-descriptions-item label="项目名称" label-class-name="my-label">{{ chooseProject.projectName
                }}</el-descriptions-item>
              <el-descriptions-item label="项目负责人" label-class-name="my-label">{{ chooseProject.projectLeaderUser ?
      chooseProject.projectLeaderUser.nickName : ''
                }}</el-descriptions-item>
              <el-descriptions-item label="承担部门" label-class-name="my-label">
                <el-tag size="small">{{ chooseProject.undertakingDeptName }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="项目类型" label-class-name="my-label">{{ chooseProject.projectType
                }}</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
          <el-form-item label="借款明细">
            <table border="1" class="table">
              <tr>
                <td style="width:50px;">序号</td>
                <td style="width:200px">开支项目</td>
                <td>单位</td>
                <td>单价</td>
                <td>数量</td>
                <td>申请金额</td>
                <td v-if="form.borrowUsage == 0 || form.borrowUsage == 1">项目管理部校核金额</td>
                <td v-if="form.borrowUsage == 0 || form.borrowUsage == 1">分管领导审核金额</td>
              </tr>
              <tr v-for="(detail, index) in detailList" :key="index">
                <td>
                  {{ index + 1 }}
                </td>
                <td>
                  <el-input v-model="detail.borrowItem" type="textarea" :disabled="taskName != '借款申请'"></el-input>
                </td>
                <td>
                  <el-input v-model="detail.unit" :disabled="taskName != '借款申请'"></el-input>
                </td>
                <td>
                  <el-input v-model="detail.price" @change="calculateAmount(detail)" :disabled="taskName != '借款申请'"></el-input>
                </td>
                <td>
                  <el-input v-model="detail.quantity" @change="calculateAmount(detail)" :disabled="taskName != '借款申请'"></el-input>
                </td>
                <td>
                  <el-input v-model="detail.applyAmount" :disabled="taskName != '借款申请'"></el-input>
                </td>
                <td v-if="form.borrowUsage == 0 || form.borrowUsage == 1">
                  <el-input v-model="detail.xmAmount" :disabled="taskName != '项目部审核'"
                    @change="calculateXmAmount(detail)"></el-input>
                </td>
                <td v-if="form.borrowUsage == 0 || form.borrowUsage == 1">
                  <el-input v-model="detail.managerAmount" :disabled="taskName != '分管审核'"
                    @change="calculateManagerAmount(detail)"></el-input>
                </td>
                <td>
                  <el-button type="danger" icon="el-icon-minus" size="mini" circle  :disabled="taskName != '借款申请'"
                    @click="deleDetailItem(index)"></el-button>
                </td>
              </tr>
            </table>
            <el-button icon="el-icon-plus" size="mini" @click="addDetailList()" type="primary" plain :disabled="taskName != '借款申请'"></el-button>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="6" :xs="24">
              <el-form-item label="申请金额" prop="applyAmount">
                <el-input v-model="form.applyAmount" placeholder="请输入申请金额" :disabled="taskName != '借款申请'" />
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="24">
              <el-form-item label="核准金额" prop="managerAmount">
                <el-input v-model="form.managerAmount" placeholder="请输入核准金额" :disabled="taskName != '分管审核' && taskName != '党工团审核'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="申请人说明" prop="remark">
            <el-input type="textarea" v-model="form.remark" placeholder="请输入申请人说明" :disabled="taskName != '借款申请'" />
          </el-form-item>
          <el-divider></el-divider>
          <!-- 非党工团审核 -->
          <div v-if="form.borrowUsage == 0 || form.borrowUsage == 1">
            <el-form-item label="部门负责人意见" prop="deptComment">
              <el-input type="textarea" v-model="form.deptComment" placeholder="请输入部门负责人意见"
                :disabled="taskName != '部门审核'" />
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px" v-if="showFormItem('部门审核')">
                  <span class="auditor"> {{ form.deptUser ? form.deptUser.nickName : deptUser }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px" v-if="showFormItem('部门审核')">
                  <span> {{ form.deptTime ? form.deptTime : deptTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="项目部校核意见" prop="xmComment">
              <el-input type="textarea" v-model="form.xmComment" placeholder="请输入项目部校核意见"
                :disabled="taskName != '项目部审核'" />
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px" v-if="showFormItem('项目部审核')">
                  <span class="auditor"> {{ form.xmUser ? form.xmUser.nickName : xmUser }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px" v-if="showFormItem('项目部审核')">
                  <span> {{ form.xmTime ? form.xmTime : xmTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="分管领导审核意见" prop="managerComment">
              <el-input type="textarea" v-model="form.managerComment" placeholder="请输入分管领导审核意见"
                :disabled="taskName != '分管审核'" />
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px" v-if="showFormItem('分管审核')">
                  <span class="auditor"> {{ form.managerUser ? form.managerUser.nickName : managerUser }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px" v-if="showFormItem('分管审核')">
                  <span> {{ form.managerTime ? form.managerTime : managerTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="总经理审批意见" prop="zjlComment">
              <el-input type="textarea" v-model="form.zjlComment" placeholder="请输入总经理审批意见"
                :disabled="taskName != '总经理审核'" />
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px" v-if="showFormItem('总经理审核')">
                  <span class="auditor"> {{ form.zjlUser ? form.zjlUser.nickName : zjlUser }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px" v-if="showFormItem('总经理审核')">
                  <span> {{ form.zjlTime ? form.zjlTime : zjlTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <!-- 党工团审核 -->
          <div v-if="form.borrowUsage != 0 && form.borrowUsage != 1">
            <el-form-item :label="dgtLabel" prop="unionComment">
              <el-input type="textarea" v-model="form.unionComment" placeholder="请输入审核意见"
                :disabled="taskName != '党工团审核'" />
            </el-form-item>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px" v-if="showFormItem('党工团审核')">
                  <span class="auditor"> {{ form.unionUser ? form.unionUser.nickName : unionUser }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px" v-if="showFormItem('党工团审核')">
                  <span> {{ form.unionTime ? form.unionTime : unionTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
          </div>


          <el-form-item label="财务部支付备注" prop="cwComment">
            <el-input type="textarea" v-model="form.cwComment" placeholder="请输入财务部支付备注"
              :disabled="taskName != '财务处理'" />
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <el-form-item label="经办人：" label-width="120px" v-if="showFormItem('财务处理')">
                <span class="auditor"> {{ form.cwUser ? form.cwUser.nickName : cwUser }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="支付日期：" style="margin-left:20px" prop="lendTime" v-if="showFormItem('财务处理')">
                <el-date-picker style="width:160px;" v-model="form.lendTime" value-format="yyyy-MM-dd" type="date"
                  placeholder="选择日期" :disabled="taskName != '财务处理'">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: center;">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-col>
      <el-col :span="6" :xs="24">
        <el-card>
          <h2 style="text-align: center;">流程进度</h2>
          <div>
            <flow :flowData="flowData" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import { getUsersDeptLeader, getUsersDeptLeaderByDept, getUsersManageLeaderByDept } from '@/api/system/post.js'
import { listBorrow, getBorrow, delBorrow, addBorrow, updateBorrow } from "@/api/oa/borrow/borrow";
import { getBorrowDetail, addBorrowDetail, updateBorrowDetail } from "@/api/oa/borrow/borrowDetail";
import { listProject, getProject } from "@/api/oa/project/project";
import flow from '@/views/flowable/task/todo/detail/flow'
import { flowXmlAndNode } from "@/api/flowable/definition";
import { complete, getNextFlowNode } from "@/api/flowable/todo";

export default {
  components: {
    flow
  },
  name: "Borrow",
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      deptUser: '',
      xmUser: '',
      managerUser: '',
      zjlUser: '',
      unionUser:'',
      cwUser: '',
      deptTime: '',
      xmTime: '',
      managerTime: '',
      zjlTime: '',
      unionTime:'',
      lendTime: '',
      // 遮罩层
      loading: true,
      detail: {},
      detailList: [
        {
          borrowItem: '',
          unit: '',
          price: '',
          quantity: '',
          applyAmount: '',
          xmAmount: '',
          managerAmount: '',
        }
      ],
      projectList: [],
      chooseProject: {},
      isSelect: false,
      // 表单参数
      form: {
        borrowUsage: '0',
        user: {
          nickName: '',
        },
        dept: {
          deptName: '',
        },
        applyDate: undefined,
      },
      // 表单校验
      rules: {
      },
      formTotal: 0,
      flowData: {},
      isProject: true,
      deptId: undefined,
      dgtLabel: '工会审核意见'
    };
  },
  created() {
    if (this.taskName == '部门审核') {
      this.deptUser = this.$store.getters.name;
      this.deptTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    if (this.taskName == '分管审核') {
      this.managerUser = this.$store.getters.name;
      this.managerTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    if (this.taskName == '项目部审核') {
      this.xmUser = this.$store.getters.name;
      this.xmTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    if (this.taskName == '总经理审核') {
      this.zjlUser = this.$store.getters.name;
      this.zjlTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    if (this.taskName == '党工团审核') {
      this.unionUser = this.$store.getters.name;
      this.unionTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    if (this.taskName == '财务处理') {
      this.cwUser = this.$store.getters.name;
      this.lendTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    this.form.applyDate = new Date();
    this.form.user.nickName = this.$store.getters.name;
    this.form.dept.deptName = this.$store.getters.deptName;
    this.deptId = this.$store.getters.deptId;
    this.getProjectList();
    flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
      this.flowData = res.data;
    })
  },
  mounted() {
    this.initForm();
  },
  methods: {
    initForm() {
      getBorrowDetail(this.taskForm.formId).then(res => {
        if (res.data.length != 0) {
          this.detailList = res.data
        }
      });
      getBorrow(this.taskForm.formId).then(res => {
        console.log(res);
        if (this.isEmptyObject(res.data)) {
          this.formTotal = 0;
          this.form.applier = this.$store.getters.userId;
        }
        else {
          this.formTotal = 1;
          this.form = res.data;
          this.hanldeChangeType()
        }
        this.loading = false;
      })
    },
    // 查询项目列表
    getProjectList() {
      listProject({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.projectList = response.rows;
      })
    },
    // 选择项目
    handleSelectProject(val) {
      if (val != "" && val != undefined && val != null) {
        getProject(val).then(res => {
          this.chooseProject = res.data;
          this.isSelect = true
        })
      } else {
        this.isSelect = false
      }
    },
    // 取消按钮
    cancel() {
      this.reset();
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    deleDetailItem(index) {
      let arr = this.detailList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
    },
    addDetailList() {
      this.detailList.push({
        borrowItem: '',
        unit: '',
        price: '',
        quantity: '',
        applyAmount: '',
        xmAmount: '',
        managerAmount: '',
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formTotal != 0) {
            for (let detail of this.detailList) {
              updateBorrowDetail(detail);
            }
            updateBorrow(this.form).then(response => {
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              if (this.taskName == '部门审核') {
                getUsersDeptLeaderByDept({ deptId: 107 }).then(res => {
                  let userId = res.data.userId;
                  this.$set(this.taskForm.variables, "approval", userId);
                  this.$set(this.taskForm.variables, "isProject", this.isProject);
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  });
                });
              }
              else if (this.taskName == '项目部审核') {
                getUsersManageLeaderByDept({ deptId: this.form.applyDept }).then(res => {
                  let userId = res.data.userId;
                  this.$set(this.taskForm.variables, "approval", userId);
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  });
                });
              }
              else if (this.taskName == '分管审核') {
                this.$set(this.taskForm.variables, "approval", 2);
                complete(this.taskForm).then(response => {
                  this.$modal.msgSuccess(response.msg);
                  this.$emit('goBack')
                });
              }
              else if (this.taskName == '总经理审核') {
                getUsersDeptLeaderByDept({ deptId: 106 }).then(res => {
                  let userId = res.data.userId;
                  this.$set(this.taskForm.variables, "approval", userId);
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  });
                });
              }
              else if (this.taskName == '党工团审核') {
                complete(this.taskForm).then(response => {
                  this.$modal.msgSuccess(response.msg);
                  this.$emit('goBack')
                });
              }
              else if (this.taskName == '财务处理') {
                complete(this.taskForm).then(response => {
                  this.$modal.msgSuccess(response.msg);
                  this.$emit('goBack')
                });
              }
            })
          } else {
            for (let detail of this.detailList) {
              detail.borrowId = this.taskForm.formId;
              addBorrowDetail(detail);
            }
            this.form.borrowId = this.taskForm.formId;
            addBorrow(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              let userId;
              if (this.deptId == 0) {
                if (this.form.borrowUsage == 2 || this.form.borrowUsage == 3) {
                  userId = this.publicData.publicData.partySecretary
                } else {
                  userId = this.publicData.publicData.leagueSecretary
                }
                this.$set(this.taskForm.variables, "dept", this.deptId);
                this.$set(this.taskForm.variables, "approval", userId);
                complete(this.taskForm).then(response => {
                  this.$modal.msgSuccess(response.msg);
                  this.$emit('goBack')
                });
              } else {
                getUsersDeptLeader({ userId: this.$store.getters.userId }).then(res => {
                  let userId = res.data.userId;
                  this.$set(this.taskForm.variables, "approval", userId);
                  this.$set(this.taskForm.variables, "dept", this.deptId);
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  });
                })
              }

            })
          }
        }
      });
    },
    showFormItem(name) {
      debugger
      let isShow = false;
      if (name == '借款申请')
        isShow = true;
      else if (name == '部门审核')
        isShow = (this.taskName != '借款申请');
      else if (name == '项目部审核')
        isShow = (this.taskName != '借款申请' && this.taskName != '部门审核');
      else if (name == '分管审核')
        isShow = (this.taskName != '借款申请' && this.taskName != '部门审核' && this.taskName != '项目部审核');
      else if (name == '总经理审核')
        isShow = (this.taskName == '总经理审核' || this.taskName == '财务处理');
      else if(name == '党工团审核')
        isShow = (this.taskName == '党工团审核' || this.taskName == '财务处理');
      else if (name == '财务处理')
        isShow = (this.taskName == '财务处理');
      return isShow;
    },
    calculateAmount(detail) {
      let total = Number(detail.price) * Number(detail.quantity);
      this.$set(detail, "applyAmount", total.toFixed(2));
      this.getTotal("applyAmount", "applyAmount", this.detailList);
    },
    calculateXmAmount(detail) {
      this.getTotal("xmAmount", "managerAmount", this.detailList);
    },
    calculateManagerAmount(detail) {
      this.getTotal("managerAmount", "managerAmount", this.detailList);
    },
    getTotal(name1, name2, list) {
      let sum = 0;
      for (let user of list) {
        sum = sum + Number(user[name1]);
      }
      this.form[name2] = sum.toFixed(2);
    },
    // 修改借款类型
    hanldeChangeType() {
      debugger
      if (this.form.borrowUsage == '0') {
        this.dgtLabel = '工会审核意见'
        this.isProject = true
      } else {
        this.isProject = false
      }
      if (this.form.borrowUsage == '2' || this.form.borrowUsage == '3' || this.form.borrowUsage == '4') {
        this.deptId = 0
        if (this.form.borrowUsage == '2') {
          this.dgtLabel = '工会审核意见'
        } else if (this.form.borrowUsage == '3') {
          this.dgtLabel = '党委审核意见'
        }else{
          this.dgtLabel = '团委审核意见'
        }
      }
    },
  }
};
</script>

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

.auditor {
  font-family: '华文行楷';
  font-size: 20px;
}

table {
  text-align: center;
  border-collapse: collapse;

  td {
    padding: 5px;
  }
}
</style>