<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="flowDisabled ? 18 : 24" :xs="24">
        <h2 class="text-center">保证金审批表</h2>
        <el-divider></el-divider>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12" :xs="24">
              <el-form-item label="保证金类型" prop="depositType">
                <el-radio-group v-model="form.depositType" @change="changeDepositType" :disabled="taskName != '保证金申请'">
                  <el-radio :label="'0'">投标保证金</el-radio>
                  <el-radio :label="'1'">合同履约保证金</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item label="预计退还日期" prop="returnTime">
                <el-date-picker clearable v-model="form.returnTime" type="date" value-format="yyyy-MM-dd"
                  placeholder="请选择预计退还日期" :disabled="taskName != '保证金申请'">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="投标项目名称" prop="tenderId" v-if="tenderOpen">
            <!-- <el-select v-model="form.tenderId" filterable placeholder="请选择" @change="handleSelectTender"
              :disabled="taskName != '保证金申请'" clearable>
              <el-option v-for="item in tenderList" :key="item.value" :label="item.projectName" :value="item.tenderId">
              </el-option>
            </el-select> -->
            <el-button type="primary" size="mini" @click="tbOpen = true" v-if="taskName == '保证金申请'">选择投标项目</el-button>
            <el-descriptions border v-if="isTenderSelect" style="margin-top: 10px;" :column="1">
              <el-descriptions-item label="投标项目名称" label-class-name="my-label">
                {{ chooseTender.projectName }}
              </el-descriptions-item>
              <el-descriptions-item label="投标保证金" label-class-name="my-label">{{ chooseTender ? chooseTender.deposit : ''
              }}</el-descriptions-item>
              <el-descriptions-item label="招标业主" label-class-name="my-label">{{ chooseTender ? (chooseTender.partyA ?
                chooseTender.partyA.partyAName : '') : '' }}</el-descriptions-item>
              <el-descriptions-item label="招标代理人" label-class-name="my-label">{{ chooseTender ? (chooseTender.agent) : ''
              }}</el-descriptions-item>
              <el-descriptions-item label="联系人及电话" label-class-name="my-label">{{ chooseTender ? (chooseTender.agentPerson
                + chooseTender.agentPhone) : ''
              }}</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
          <el-form-item label="合同名称" prop="contractId" v-if="contractOpen">
            <!-- <el-select v-model="form.contractId" filterable placeholder="请选择" @change="handleSelectContract"
              :disabled="taskName != '保证金申请'" clearable>
              <el-option v-for="item in contractList" :key="item.value"
                :label="item.tender ? item.tender.projectName : item.contractCode" :value="item.contractId">
              </el-option>
            </el-select> -->
            <el-button type="primary" size="mini" @click="htOpen = true" v-if="taskName == '保证金申请'">选择合同</el-button>
            <el-descriptions border v-if="isContractSelect" style="margin-top: 10px;" :column="1">
              <el-descriptions-item label="合同编码" label-class-name="my-label">{{ chooseContract ?
                chooseContract.contractCode : ''
              }}</el-descriptions-item>
              <el-descriptions-item label="履约保证金" label-class-name="my-label">{{ chooseContract ? chooseContract.deposit :
                ''
              }}</el-descriptions-item>
              <el-descriptions-item label="甲方单位" label-class-name="my-label">{{ chooseContract ? (chooseContract.tender ?
                chooseContract.tender.aPerson : '') : ''
              }}</el-descriptions-item>
              <el-descriptions-item label="联系人及电话" label-class-name="my-label">
                {{ chooseContract ? (chooseContract.tender ? chooseContract.tender.aPerson + chooseContract.tender.aPhone
                  : '') : '' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-form-item>
          <el-row>
            <el-col :span="12" :xs="24">
              <el-form-item label="开户名称" prop="accountName">
                <el-input v-model="form.accountName" placeholder="请输入开户名称" :disabled="taskName != '保证金申请'" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item label="开户银行" prop="accountBank">
                <el-input v-model="form.accountBank" placeholder="请输入开户银行" :disabled="taskName != '保证金申请'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" :xs="24">
              <el-form-item label="银行卡号" prop="cardNumber">
                <el-input v-model="form.cardNumber" placeholder="请输入银行卡号" :disabled="taskName != '保证金申请'" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item label="保证金形式" prop="depositWay">
                <el-select v-model="form.depositWay" filterable placeholder="请选择" :disabled="taskName != '保证金申请'"
                  clearable>
                  <el-option v-for="item in depositWayList" :key="item.value" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="申请说明" prop="applyReason">
            <el-input type="textarea" :rows="2" v-model="form.applyReason" placeholder="请输入申请说明"
              :disabled="taskName != '保证金申请'" />
          </el-form-item>
          <el-form-item label="相关附件" prop="applyDocument">
            <FileUpload v-if="form.applyDocument == null || form.applyDocument == ''" :disabled="taskName != '保证金申请'"
              :limit="1" :filePathName="'保证金/申请附件'" :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']"
              @input="getApplyPath"></FileUpload>
            <div v-if="form.applyDocument && taskName != '保证金申请'">
              <!-- <file-item :document="form.applyDocument"></file-item> -->
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.applyDocument}`)">
                {{ getFileName(form.applyDocument) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.applyDocument}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
            </div>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="6" :offset="12" :xs="24">
              <el-form-item label="申请人" label-width="120px">
                <span class="auditor"> {{ form.applierUser ? form.applierUser.nickName : applierUser }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="24">
              <el-form-item label="申请日期" label-width="120px">
                <span> {{ form.applyTime ? form.applyTime : applyTime }} </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider></el-divider>
          <el-form-item label="分管审批意见" prop="managerComment">
            <el-input type="textarea" v-model="form.managerComment" placeholder="请输入分管审批意见"
              :disabled="taskName != '分管审批'" />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="6" :offset="12" :xs="24">
              <el-form-item label="审批人" label-width="120px" v-if="taskName != '保证金申请'">
                <span class="auditor"> {{ form.managerUser ? form.managerUser.nickName : managerUser }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="24">
              <el-form-item label="审批日期" label-width="120px" v-if="taskName != '保证金申请'">
                <span> {{ form.managerTime ? form.managerTime : managerTime }} </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider></el-divider>
          <el-form-item label="汇款凭证" prop="remitDocument">
            <FileUpload v-if="taskName == '财务处理'" :disabled="taskName != '财务处理'" :limit="1" :filePathName="'保证金/汇款凭证'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getRemitPath"></FileUpload>
            <div v-if="form.remitDocument && taskName != '财务处理'">
              <!-- <file-item :document="form.remitDocument"></file-item> -->
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.remitDocument}`)">
                {{ getFileName(form.remitDocument) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.remitDocument}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
            </div>
          </el-form-item>
          <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="12" :xs="24">
              <el-form-item label="汇款日期" prop="remitTime">
                <el-date-picker clearable v-model="form.remitTime" type="date" value-format="yyyy-MM-dd"
                  placeholder="请选择汇款日期" :disabled="taskName != '财务处理'">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item label="退还时间" prop="backTime">
                <el-date-picker clearable v-model="form.backTime" type="date" value-format="yyyy-MM-dd"
                  placeholder="请选择退还时间" :disabled="taskName != '财务处理'">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6" :offset="12" :xs="24">
              <el-form-item label="处理人" label-width="120px" v-if="taskName == '财务处理' || taskName == ''">
                <span class="auditor"> {{ form.cwUser ? form.cwUser.nickName : cwUser }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="6" :xs="24">
              <el-form-item label="处理日期" label-width="120px" v-if="taskName == '财务处理' || taskName == ''">
                <span> {{ form.cwTime ? form.cwTime : cwTime }} </span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: center;" v-if="flowDisabled">
          <el-button type="primary" @click="submitForm" v-if="taskName != '财务处理'">提 交</el-button>
          <el-button @click="submitForm" type="danger" v-if="taskName == '财务处理'">结束</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>
    <el-dialog title="选择投标项目" :visible.sync="tbOpen" width="70%" append-to-body>
      <choose-tender @choose="confirmTender"></choose-tender>
    </el-dialog>
    <el-dialog title="选择合同" :visible.sync="htOpen" width="70%" append-to-body>
      <choose-contract @choose="confirmContract" @close="htOpen == false"></choose-contract>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import { listContract, getContract } from "@/api/oa/contract/contract";
import { listTender, getTender } from "@/api/oa/tender/tender";
import { listDeposit, getDeposit, delDeposit, addDeposit, updateDeposit } from "@/api/oa/deposit/deposit";
import { getUsersManageLeader, getUsersDeptLeaderByDept, getUsersViceDeptLeaderByDept } from '@/api/system/post.js'
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import flow from '@/views/flowable/task/todo/detail/flow'
import { flowXmlAndNode } from "@/api/flowable/definition";
import FileItem from '../business/fileItem.vue';
import ChooseTender from '../components/chooseTender.vue';
import ChooseContract from '../components/chooseContract.vue';

export default {
  components: {
    flow,
    FileItem,
    ChooseTender,
    ChooseContract
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
    flowDisabled: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    'taskForm.formId'() {
      this.initForm();
    }
  },
  name: "Deposit",
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      tbOpen: false,
      htOpen: false,
      applierUser: '',
      applyTime: undefined,
      managerUser: '',
      managerTime: undefined,
      cwUser: '',
      cwTime: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // cmc保证金审批表格数据
      depositList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        depositType: null,
        tenderId: null,
        contractId: null,
        returnTime: null,
        accountName: null,
        accountBank: null,
        cardNumber: null,
        depositWay: null,
        applier: null,
        applyTime: null,
        applyReason: null,
        applyDocument: null,
        managerComment: null,
        managerTime: null,
        managerUserId: null,
        remitTime: null,
        cwTime: null,
        backTime: null,
        cwComment: null,
        cwUserId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      tenderOpen: false,
      contractOpen: false,
      chooseTender: {},
      chooseContract: {},
      isTenderSelect: false,
      isContractSelect: false,
      formTotal: 0,
      flowData: {},
      tenderList: [],
      contractList: [],
      depositWayList: [{ id: '1', name: '电汇' }, { id: '2', name: '现金' }, { id: '3', name: '汇票' }],
    };
  },
  mounted() {
    this.initRules();
    this.initForm();
  },
  created() {
    if (this.taskName == '保证金申请') {
      this.applierUser = this.$store.getters.name;
      this.applyTime = 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.cwUser = this.$store.getters.name;
      this.cwTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    this.getTenderList();
    this.getContractList();
    this.getList();
    if (this.flowDisabled)
      flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
        this.flowData = res.data;
      })
  },
  methods: {
    initRules() {
      if (this.taskName == '保证金申请') {
        this.rules = {
          accountName: [
            { required: true, message: '请输入开户名称', trigger: 'blur' },
          ],
          accountBank: [
            { required: true, message: '请输入开户银行', trigger: 'blur' },
          ],
          cardNumber: [
            { required: true, message: '请输入银行卡号', trigger: 'blur' },
          ],
          depositWay: [
            { required: true, message: '请选择保证金形式', trigger: 'change' },
          ],
        }
      } else if (this.taskName == '分管审批') {
        this.rules = {
          managerComment: [
            { required: true, message: '请输入分管领导审批意见', trigger: 'blur' }
          ]
        }
      } else if (this.taskName == '财务处理') {
        this.rules = {
          remitTime: [
            { required: true, message: '请输入汇款时间', trigger: 'blur' },
          ],
          backTime: [
            { required: true, message: '请输入退还时间', trigger: 'blur' },
          ],
        }
      }
    },
    // 初始化表单
    initForm() {
      getDeposit(this.taskForm.formId).then(res => {
        if (this.isEmptyObject(res.data)) {
          this.formTotal = 0;
          this.form.applier = this.$store.getters.userId;
          this.form.applyTime = parseTime(new Date(), '{y}-{m}-{d}')
        }
        else {
          this.formTotal = 1;
          this.form = res.data;
          if (res.data.tenderId) {
            getTender(res.data.tenderId).then(response => {
              this.chooseTender = response.data;
              this.isTenderSelect = true;
              this.form.depositType = '0';
              this.tenderOpen = true;
            })
          }
          if (res.data.contractId) {
            getContract(res.data.contractId).then(response => {
              this.chooseContract = response.data;
              this.isContractSelect = true;
              this.form.depositType = '1';
              this.contractOpen = true;
            })
          }
          this.loading = false
        }
      })
    },
    /** 查询cmc保证金审批列表 */
    getList() {
      this.loading = true;
      listDeposit(this.queryParams).then(response => {
        this.depositList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 查询项目列表
    getTenderList() {
      this.loading = true
      listTender({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.tenderList = response.rows;
      })
    },
    // 查询合同列表
    getContractList() {
      this.loading = true
      listContract({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.contractList = response.rows;
      })
    },
    // 选择合同
    handleSelectContract(val) {
      if (val != "" && val != undefined && val != null) {
        getContract(val).then(res => {
          this.chooseContract = res.data;
          this.isContractSelect = true;
        })
      } else {
        this.isContractSelect = false
      }
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    changeDepositType(val) {
      if (val == '0') {
        this.tenderOpen = true;
        this.contractOpen = false;
      }
      else if (val == '1') {
        this.tenderOpen = false;
        this.contractOpen = true;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formTotal != 0) {
            updateDeposit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              if (this.taskName == '保证金申请') {
                let approvalList = [];
                getUsersManageLeader({ userId: this.$store.getters.userId }).then(res => {
                  let userId = res.data[0].userId;
                  approvalList.push(userId)
                  this.$set(this.taskForm.variables, "approvalList", approvalList);
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  })
                })
              }
              if (this.taskName == '分管审批') {
                let approvalList = [];
                getUsersDeptLeaderByDept({ deptId: 106 }).then(res => {
                  approvalList.push(res.data.userId);
                  getUsersViceDeptLeaderByDept({ deptId: 106 }).then(res1 => {
                    approvalList.push(res1.data.userId);
                    this.$set(this.taskForm.variables, "approvalList", approvalList);
                    complete(this.taskForm).then(response => {
                      this.$modal.msgSuccess(response.msg);
                      this.$emit('goBack')
                    })
                  })
                });
              }
              else if (this.taskName == '财务处理') {
                if (this.form.backTime != undefined) {
                  complete(this.taskForm).then(response => {
                    this.$modal.msgSuccess(response.msg);
                    this.$emit('goBack')
                  })
                }
              }
            })
          } else {
            this.form.depositId = this.taskForm.formId;
            addDeposit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              let approvalList = [];
              getUsersManageLeader({ userId: this.$store.getters.userId }).then(res => {
                let userId = res.data[0].userId;
                approvalList.push(userId)
                this.$set(this.taskForm.variables, "approvalList", approvalList);
                complete(this.taskForm).then(response => {
                  this.$modal.msgSuccess(response.msg);
                  this.$emit('goBack')
                })
              })
            })
          }
        }
      });
    },
    confirmTender(val) {
      if (val != "" && val != undefined && val != null) {
        this.chooseTender = val;
        this.isTenderSelect = true;
        this.form.tenderId = val.tenderId;
        this.tbOpen = false;
      }
    },
    confirmContract(val) {
      if (val != "" && val != undefined && val != null) {
        this.chooseContract = val;
        this.isContractSelect = true;
        this.form.contractId = val.contractId;
        this.htOpen = false;
      }
    },
    // 选择项目
    handleSelectTender(val) {
      if (val != "" && val != undefined && val != null) {
        getTender(val).then(res => {
          this.chooseTender = res.data;
          this.isTenderSelect = true;
        })
      } else {
        this.isTenderSelect = false
      }
    },
    getApplyPath(val) {
      let arr = val.split('/upload')
      this.form.applyDocument = arr[1]
      if (val == "") {
        this.form.applyDocument = ""
      }
    },
    getRemitPath(val) {
      let arr = val.split('/upload')
      this.form.remitDocument = arr[1]
      if (val == "") {
        this.form.remitDocument = ""
      }
    },
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/styles/element-reset.scss";
</style>
