<template>
  <view>
    <view style="padding: 10px 0px 66px 0px;min-height: 100px">
      <!--标题-->
      <view style="text-align:center">
        <text class="title">{{title}}</text>
      </view>
      <view class="card">
        <!--表单-->
        <invoiceModule ref="invoiceModule" :invoice="jsonData" :formData="formData"></invoiceModule>
        <transferRecordsModule :historicTaskList="historicTaskList"></transferRecordsModule>
        <!--审核意见-->
        <view v-if="type === 'audit'">
          <view class="divider">
            <text class="divider-content"><span style="color: red">*</span> 审批意见</text>
          </view>
          <textarea :rows="5" maxlength="500" placeholder="请填写审核意见：" v-model="comments" show-word-limit></textarea>
        </view>
        <!--操作按钮-->
        <view class="bottom-wrap  flex">
          <view class="flex-sub"
                v-for="(button, index) in buttons" :key="index" >
            <u-button type="primary" class=" buttonBox" :color="colors[index]" @click="submit(button, buttons)" :text="button.name"></u-button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import InvoiceModule from './InvoiceModule.vue';
  import TransferRecordsModule from './TransferRecordsModule.vue';
  import ccpmService from '@/api/centerservice/ccpm/CcpmService'

  export default {
    onLoad: function (option) {
      this.flow = JSON.parse(decodeURIComponent(option.flow));
      this.businessId = this.flow.id
      this.processDefKey = this.flow.processDefKey
      this.title = this.flow.title
      this.type = this.flow.type
      this.jsonData = []
      this.comments = ''
    },
    data () {
      return {
        buttons: [
          {code: '_flow_agree', name: '同意'},
          {code: '_flow_reject', name: '驳回'},
          {code: '_flow_close', name: '关闭'},
        ],
        colors: [ '#3c9cff', '#f56c6c', '#5ac725', '#f9ae3d', '#89c152',
          '#c38cc1', '#448aca', '#73d1f1', '#ffb34b', '#f18080',
          '#88a867', '#bfbf39', '#94d554', '#f19ec2', '#afaae4',
          '#86cefa', '#98d1ee', '#72dcdc', '#9acdcb', '#77b1cc', '#80a7dc'
        ],
        flow: null,
        formData: {
          name: '',
          email: '',
          remarks: ''
        },
        jsonData: [],
        historicTaskList: [],
        title: '',
        businessId: '',
        type: '',
        processDefKey: '',
        comments: '' // 审核意见
      }
    },
    activated () {
      this.init()
    },
    created () {
      this.init()
    },
    components: {
      InvoiceModule,
      TransferRecordsModule,
    },
    methods: {
      // 初始化
      init () {
        this.$nextTick(async () => {
          await ccpmService.getByIdGenerate(this.businessId, this.processDefKey).then((data)=>{
            if (data) {
              this.jsonData = Array.isArray(data) ? data : [data];
              this.historicTaskList = data.histoicFlow
            } else {
            }
          })

        })
      },
      // 关闭
      close () {
        this.jsonData = []
        this.comments = ''
        uni.navigateTo({
          url: '/pages/workbench/task/TodoList'
        })
      },
      // 同意
      async agree () {
        const inputForm = this.$refs.invoiceModule.getInputForm();
        return new Promise(  (resolve, reject) => {
          // 表单规则验证
          // ...

          let errors = [];

          if (this.isEmpty(inputForm.invoiceDate)) {
            errors.push('开票时间不能为空');
          }

          let acc = 0
          let i = inputForm.workAccountList.length;
          for (let j = 0; j < i; j++) {
            let k = j + 1;
            if (this.isEmpty(inputForm.workAccountList[j].number)) {
              errors.push('发票明细中第' + k + ' 条数据的 “发票号” 为空');
            }
            if (this.isEmpty(inputForm.workAccountList[j].account)) {
              errors.push('发票明细中第' + k + ' 条数据的 “开票金额” 为空');
            }
            acc = (acc + parseFloat(parseFloat(inputForm.workAccountList[j].account).toFixed(2)))
          }

          if (parseFloat(acc).toFixed(2) !== parseFloat(inputForm.money).toFixed(2)) {
            errors.push('发票明细中 “开票金额”总和 与发票详情中 “发票金额” 不等');
          }

          let errorDetected = true; // 布尔变量用于检测是否有错误发生
          inputForm.workAccountList.forEach( async(item, index) => {
            const numberString = item.number.trim(); // 去除空格
            // 查询是否已存在
            await ccpmService.queryByNumber(numberString).then((data) => {
              if (data === true) {
                errorDetected = false
                errors.push('“发票号” 已存在，请重新输入');
              }
            });
            if (errorDetected) {
              inputForm.workAccountList.forEach((item2, index2) => {
                if (index !== index2) {
                  if (item.number === item2.number) {
                    errors.push('发票明细中第 ' + (index + 1) + ' 条数据的 “发票号” 存在重复');
                  }

                }
              })
            }

          })

          if (errors.length > 0) {
            // 存在错误，显示提示信息
            errors.forEach(error => {
              uni.showToast({
                title: error,
                icon: 'none',
                duration: 2000
              });
            });
            reject('Form validation failed');
          } else {

            if (this.isEmpty(this.comments)) {
              uni.showToast({ title: '请填写审批意见!', icon: "error" });
            } else {
              let jsonData = JSON.stringify(inputForm)
              ccpmService.invoiceAudit(this.businessId, 'yes', this.comments, this.processDefKey,jsonData).then((data) => {
                if (data.success) {
                  this.$message.success(data.message)
                  this.close()
                } else {
                  this.$message.error(data.message)
                }
              }).catch(() => {

              })
            }
          }
        });
      },
      // 驳回
      reject () {
        const inputForm = this.$refs.invoiceModule.getInputForm();
        if (this.isEmpty(this.comments)) {
          uni.showToast({ title: '请填写审批意见', icon: "error" });
        } else {

          // 弹窗 二次确认
          uni.showModal({
            content: '确定驳回此报销申请吗?',
            success: async (res) => {
              if (res.confirm) {
                let jsonData = JSON.stringify(inputForm)
                ccpmService.invoiceAudit(this.businessId, 'no', this.comments, this.processDefKey,jsonData).then((data) => {

                  if (data.success) {
                    this.$message.success(data.message)
                    this.close()
                  } else {
                    this.$message.error(data.message)
                  }
                }).catch(() => {

                })
              }
            },
          })
        }
      },
      isEmpty(value) {
        let result = false;
        if (value == null || value == undefined) {
          result = true;
        }
        if (typeof value == 'string' && (value.replace(/\s+/g, "") == "" || value == "")) {
          result = true;
        }
        if (typeof value == "object" && value instanceof Array && value.length === 0) {
          result = true;
        }
        return result;
      },
      isNotEmpty (value) {
        return !this.isEmpty(value)
      },
      submit (currentBtn, buttons) {

        switch (currentBtn.code) {
          case '_flow_agree': // 同意
            this.agree()
            break
          case '_flow_reject': // 驳回
            this.reject()
            break
          case '_flow_close':// 关闭
            this.close()
            break
        }
      }
    }
  }
</script>

<style scoped>
  .title {
    font-size: 24px;
    font-weight: bold;
  }

  .card {
    padding: 15px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  }

  .divider {
    display: flex;
    align-items: center;
    margin-top: 20px;
  }

  .divider-content {
    font-size: 16px;
    color: #333;
  }

  .FlowFormFooter {
    display: flex;
    justify-content: space-around;
    margin-top: 2em;
  }

  button {
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
  }

  button[type=primary] {
    background-color: #409eff;
    color: #fff;
  }

  button[type=danger] {
    background-color: #f56c6c;
    color: #fff;
  }
</style>
