<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="18" :xs="24">
        <h2 class="text-center">品牌项目支付审批表</h2>
        <el-divider></el-divider>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="品牌项目" prop="projectId">
            <el-select v-model="form.projectId" filterable placeholder="请选择" @change="handleSelectProject"
              :disabled="taskName != '支付申请'" clearable style="width: 100%;">
              <el-option v-for="item in projectList" :key="item.value"
                :label="item.projectNumber + '-' + item.projectName" :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.partyA ?
                chooseProject.partyA.partyAName : ''
                }}</el-descriptions-item>
              <el-descriptions-item label="合作单位" label-class-name="my-label">{{ chooseProject.partner ?
                chooseProject.partner.partnerName : ''
                }}</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
          <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="approvalDocument">
            <FileUpload v-if="formTotal == 0" :disabled="taskName != '支付申请'" :limit="1" :filePathName="'品牌项目支付/审核文件'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getBrandPath"></FileUpload>
            <div v-if="formTotal == 1">
              <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.approvalDocument}`)">
                {{ getFileName(form.approvalDocument) }}
              </el-link>
              <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.approvalDocument}`"
                :underline="false" target="_blank">
                <span class="el-icon-download">下载文件</span>
              </el-link>
            </div>
          </el-form-item>
          <el-row>
            <el-col :span="6" :xs="24" :offset="12">
              <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">
              <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="财务反馈：">
            <table border="1" style="width:100%;">
              <tr>
                <td>序号</td>
                <td>到账情况</td>
                <td>到账时间</td>
                <td>操作</td>
              </tr>
              <tr v-for="(payment, index) in paymentList" :key="index">
                <td>
                  {{ index + 1 }}
                </td>
                <td>
                  <el-input type="textarea" v-model="payment.cwComment" placeholder="请输入到账情况"
                    :disabled="taskName != '财务反馈'" />
                </td>
                <td>
                  <el-date-picker clearable v-model="payment.paymentTime" type="date" value-format="yyyy-MM-dd"
                    placeholder="请选择到账时间" :disabled="taskName != '财务反馈'" style="width:100%;">
                  </el-date-picker>
                </td>
                <td>
                  <el-button type="text" style="color:#F56C6C;" size="mini" @click="deletPaymentItem(index)"
                    :disabled="taskName != '财务反馈'">删除行</el-button>
                </td>
              </tr>
            </table>
            <el-button icon="el-icon-plus" size="mini" @click="addPaymentList()" type="primary" plain
              :disabled="taskName != '财务反馈'"></el-button>
            <el-row>
              <el-col :span="6" :xs="24" :offset="12">
                <el-form-item label="签名：" label-width="120px" v-if="taskName == '财务反馈'">
                  <span class="auditor"> {{ form.cwUser ? form.cwUser.nickName : cwUser }} </span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="日期：" label-width="120px" v-if="taskName == '财务反馈'">
                  <span> {{ form.cwTime ? form.cwTime : cwTime }} </span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <div style="text-align: center;">
          <el-button type="primary" @click="submitForm" v-if="taskName == '支付申请'">提 交</el-button>
          <el-button @click="preserve()" type="warning" 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">
        <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 { getUsersDeptLeaderByDept, getUsersViceDeptLeaderByDept } from '@/api/system/post.js'
import { listBrandProject, getBrandProject } from "@/api/oa/brand/brandProject";
import { listBrandPayment, addBrandPayment, delBrandPayment } from "@/api/oa/brand/brandPayment";
import { listBrand, getBrand, delBrand, addBrand, updateBrand } from "@/api/oa/brand/brand";
import { complete, getNextFlowNode } from "@/api/flowable/todo";
import flow from '@/views/flowable/task/todo/detail/flow'
import { flowXmlAndNode } from "@/api/flowable/definition";

export default {
  components: {
    flow
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    }
  },
  name: "Brand",
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      applierUser: '',
      applyTime: undefined,
      cwUser: '',
      cwTime: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // cmc品牌项目支付审批表格数据
      brandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        applyReason: null,
        approvalDocument: null,
        applier: null,
        applyTime: null,
        cwTime: null,
        cwUserId: null
      },
      // 表单参数
      form: {},
      paymentList: [
        {
          cwComment: '',
          paymentTime: undefined
        }
      ],
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: '请选择品牌项目', trigger: 'change' },
        ],
        applyReason: [
          { required: true, message: '请输入申请支付说明', trigger: 'blur' },
        ],
        approvalDocument: [
          { required: true, message: '请上传审核文件', trigger: 'blur' },
        ],
      },
      chooseProject: {},
      isSelect: false,
      formTotal: 0,
      flowData: {},
      projectList: [],
    };
  },
  mounted() {
    this.initForm();
  },
  created() {
    if (this.taskName == '支付申请') {
      this.applierUser = this.$store.getters.name;
      this.applyTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    if (this.taskName == '财务反馈') {
      this.cwUser = this.$store.getters.name;
      this.cwTime = parseTime(new Date(), '{y}-{m}-{d}')
    }
    this.getProjectList();
    this.getList();
    flowXmlAndNode({ procInsId: this.taskForm.procInsId, deployId: this.taskForm.deployId }).then(res => {
      this.flowData = res.data;
    })
  },
  methods: {
    // 初始化表单
    initForm() {
      getBrand(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;
          listBrandPayment({ brandId: this.taskForm.formId }).then(res => {
            this.oldPaymentList = res.rows;
            if (res.rows.length > 0)
              this.paymentList = res.rows;
          });
          if (res.data.projectId) {
            getBrandProject(res.data.projectId).then(response => {
              this.chooseProject = response.data;
              this.isSelect = true
            })
          }
          this.loading = false
        }
      })
    },
    /** 查询cmc品牌项目支付审批列表 */
    getList() {
      this.loading = true;
      listBrand(this.queryParams).then(response => {
        this.brandList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 查询项目列表
    getProjectList() {
      this.loading = true
      listBrandProject({
        pageNum: 1,
        pageSize: 99999999
      }).then(response => {
        this.projectList = response.rows;
      })
    },
    // 选择项目
    handleSelectProject(val) {
      if (val != "" && val != undefined && val != null) {
        getBrandProject(val).then(res => {
          this.chooseProject = res.data;
          this.isSelect = true;
        })
      } else {
        this.isSelect = false
      }
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    addPaymentList() {
      this.paymentList.push({
        paymentCondition: "",
        paymentPercentage: "",
        paymentAmount: "",
        paymentTime: undefined,
        remark: "",
      });
    },
    deletPaymentItem(index) {
      let arr = this.paymentList;
      if (arr.length == 1) {
        return;
      }
      if (index >= 0 && index < arr.length) {
        arr.splice(index, 1);
      }
    },
    // 暂存数据
    preserve() {
      if (this.oldPaymentList.length != 0) {
        delBrandPayment([this.taskForm.formId]).then(res => {
          for (let payment of this.paymentList) {
            payment.brandId = this.taskForm.formId;
            addBrandPayment(payment);
          }
        });
      } else {
        for (let payment of this.paymentList) {
          payment.brandId = this.taskForm.formId;
          addBrandPayment(payment);
        }
      }
      updateBrand(this.form).then(res => {
        this.$message.success("保存成功");
      });
    },
    // 表单重置
    reset() {
      this.form = {
        brandId: null,
        projectId: null,
        applyReason: null,
        approvalDocument: null,
        applier: null,
        applyTime: null,
        cwTime: null,
        cwUserId: null
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formTotal != 0) {
            updateBrand(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              complete(this.taskForm).then(response => {
                this.$modal.msgSuccess(response.msg);
                this.$emit('goBack')
              })
            })
          } else {
            this.form.brandId = this.taskForm.formId;
            addBrand(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
            const params = { taskId: this.taskForm.taskId };
            getNextFlowNode(params).then(res => {
              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')
                  })
                })
              });
            })
          }
        }
      });
    },
    getBrandPath(val) {
      let arr = val.split('/upload')
      this.form.approvalDocument = arr[1]
      if (val == "") {
        this.form.approvalDocument = ""
      }
    },
    getFileName(name) {
      if (name) {
        let arr = name.split('/')
        return arr[arr.length - 1];
      }
    },
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/styles/element-reset.scss";

table {
  /*边框*/
  /* border: 1px solid black; */
  text-align: center;
  border-collapse: collapse;
  /*设置背景颜色*/
  /* background-color: #bfa; */
}
</style>