<template>
  <view class="apply-credit">
    <view class="title">{{ $t('approval.formInfo') }}</view>
    <view class="form-wrap">
      <u-form labelPosition="left" :model="form" :rules="rules" ref="form1" labelWidth='90'>
        <!-- 流程编码 -->
        <u-form-item :label="$t('approval.approvalCode')" borderBottom prop="wfCode">
          <u-input readonly v-model="form.wfCode" border="none" />
        </u-form-item>
        <!-- 流程标题 -->
        <u-form-item :label="$t('approval.approvalTitle')" borderBottom prop="flowTitle">
          <u-input :readonly="isCheckView" v-model="form.flowTitle" border="none"
            :placeholder="$t('base.common.placeholderI') + $t('approval.approvalTitle')" />
        </u-form-item>
        <!-- 紧急程度 -->
        <u-form-item :label="$t('approval.urgency')" borderBottom prop="flowUrgent" @click="showPopup('flowUrgent')">
          <u-input readonly @change="resetFlow('flowUrgent')" v-model="textForm.flowUrgent" border="none"
            :placeholder="$t('base.common.placeholderS') + $t('approval.urgency')" />
        </u-form-item>
        <!-- 调价日期 -->
        <u-form-item :label="$t('approval.priceDate')" borderBottom prop="setDate" @click="showSetDateCalendar = true">
          <u-input readonly v-model="form.setDate" border="none"
            :placeholder="$t('base.common.placeholderS') + $t('approval.priceDate')" />
        </u-form-item>
        <!-- 调价类型 -->
        <u-form-item :label="$t('approval.priceType')" borderBottom prop="priceType" @click="showPopup('priceType')">
          <u-input readonly v-model="textForm.priceType" border="none"
            :placeholder="$t('base.common.placeholderS') + $t('approval.priceType')" />
        </u-form-item>
        <!-- 执行时间 -->
        <u-form-item :label="$t('approval.carryOutDate')" borderBottom prop="beginDate" @click="showBeginDate = true">
          <u-input readonly v-model="form.beginDate" border="none"
            :placeholder="$t('base.common.placeholderS') + $t('approval.carryOutDate')" />
        </u-form-item>
        <!-- 结束时间 -->
        <u-form-item :label="$t('report.endData')" borderBottom prop="finishDate" @click="showFinishDate = true">
          <u-input readonly v-model="form.finishDate" border="none"
            :placeholder="$t('base.common.placeholderS') + $t('report.endData')" />
        </u-form-item>
        <!-- 调价明细 -->
        <u-form-item :label="$t('approval.priceDetail')" borderBottom prop="details" @click="toPage" v-if="!isCheckView">
          <u-input readonly border="none" :placeholder="$t('approval.priceDetail')" />
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>
        <!-- 备注 -->
        <u-form-item label="备注" borderBottom prop="remark">
          <u-input :readonly="isCheckView" type="textarea" v-model="form.remark" border="none" placeholder="备注信息" />
        </u-form-item>
      </u-form>
    </view>
    <view class="title">{{ $t('approval.priceDetail') }}</view>
    <view class="details-wrap">
      <template v-if="form.details.length">
        <view class="details-line details-title" :style="'width:' + 222 * 4 + 'rpx'">
          <span v-if="form.priceType == '101'">{{ $t('order.companyName') }}</span>
          <span v-if="form.priceType == '102'">{{ $t('order.region') }}</span>
          <span>{{ $t('order.materialName') }}</span>
          <span>{{ $t('approval.latestPrice') }}</span>
          <span>{{ $t('approval.adjustedPrice') }}</span>
        </view>
        <view v-for="(item, index) in form.details" :key="index" class="details-line" :style="'width:' + 222 * 4 + 'rpx'">
          <span v-if="form.priceType == '101'">{{ item.companyName }}</span>
          <span v-if="form.priceType == '102'">{{ item.blockName }}</span>
          <span class="item">{{ item.materialName }}</span>
          <span>{{ item.lastPrice || '' }}</span>
          <span>{{ item.price || '' }}</span>
        </view>
      </template>
      <template v-else>
        <u-empty mode="list" text='设置调价明细' icon="https://cdn.uviewui.com/uview/empty/list.png">
        </u-empty>
      </template>
    </view>
    <view class="title">{{ $t('approval.approvalInfo') }}</view>
    <view class="flow-wrap">
      <u-steps direction="column" :current="currentIndex">
        <u-steps-item v-for="item, index in flowList" :key="index" :title="item.title"
          :desc="item.content + (item.handleOpinion ? ` (${item.handleOpinion})` : '')">
          <span slot="time" class="time">{{ item.time }}</span>
        </u-steps-item>
      </u-steps>
    </view>
    <view class="btn-wrap" v-if="!isCheckView">
      <button type="primary" color='#4680F9' @click="submit('form1')">{{ $t('base.common.submit') }}</button>
    </view>

    <!-- 紧急程度 -->
    <PopupSelect ref="flowUrgent" kind="flowUrgent" :option="flowUrgentOptions" @onConfirm="onConfirm" />
    <!-- 调价类型 -->
    <PopupSelect ref="priceType" kind="priceType" :option="priceTypeOptions" @onConfirm="onConfirm" />
    <!-- 调价日期 -->
    <u-calendar color="#4680F9" round='25' :show="showSetDateCalendar" @confirm="onSetDateConfirm"
      @close="showSetDateCalendar = false">
    </u-calendar>
    <!-- 执行时间 -->
    <u-datetime-picker :show="showBeginDate" v-model="beginDate" @confirm="beginDateConfirm" :maxDate="4102329599000"
      @cancel="showBeginDate = false" mode="datetime"></u-datetime-picker>
    <!-- 结束时间 -->
    <u-datetime-picker :show="showFinishDate" v-model="finishDate" @confirm="finishDateConfirm"
      @cancel="showFinishDate = false" :maxDate="4102329599000" mode="datetime"></u-datetime-picker>
    <u-toast ref="loadingToast" />
  </view>
</template>

<script>
import PopupSelect from '../../components/popup-select/index'
import {
  getApprovalFlow,
  BillNumber,
  createApproval,
  getApprovalInfo,
  getApprovalFlowInfo
} from "../../api/approval"
import dayjs from 'dayjs'
export default {
  components: {
    PopupSelect,
  },
  data() {
    return {
      isCheckView: false,
      enCode: 'applyProductPrice',
      id: '',
      flowId: '',
      userInfo: {},
      showSetDateCalendar: false,
      showBeginDate: false,
      showFinishDate: false,
      beginDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      finishDate: '2099-12-30 23:59:00', //结束日期
      flow: {},
      flowList: [],
      currentIndex: 0,
      form: {
        flowId: '',
        wfCode: '',
        // billNo: '',
        flowTitle: '',
        flowUrgent: 1,
        finishDate: '2099-12-30 23:59:00', //结束日期
        setDate: dayjs().format('YYYY-MM-DD'), //登记日期
        beginDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),//执行日期
        remark: undefined, //备注
        details: [],
        priceType: '',
      },
      formcondition: {
        flowUrgent: false, //紧急程度
      },
      textForm: {
        flowUrgent: this.$t('approval.ordinary'), //紧急程度
        priceType: '',
      },
      rules: {
        flowTitle: [
          { required: true, message: this.$t('base.common.placeholderI') + this.$t('approval.approvalTitle') },
        ],
        flowUrgent: [
          { required: true, message: this.$t('base.common.placeholderS') + this.$t('approval.urgency') },
        ],
        setDate: [{ required: true, message: this.$t('base.common.placeholderS') + this.$t('approval.priceDate'), trigger: "change" }],
        beginDate: [{ required: true, message: this.$t('base.common.placeholderS') + this.$t('approval.carryOutDate'), trigger: "change" }],
        finishDate: [{ required: true, message: this.$t('base.common.placeholderS') + this.$t('report.endData'), trigger: "change" }],
        priceType: [{ required: true, message: this.$t('base.common.placeholderS') + this.$t('approval.priceType'), trigger: "change" }],
        details: [{
          required: true,
          message: "领用明细不能为空",
          validator: (rule, value, callback) => {
            if (this.form.details.length) {
              callback()
            } else {
              callback(new Error("调价信息不能为空"))
            }
          }
        }],
      },

      flowUrgentOptions: [
        { text: this.$t('approval.ordinary'), value: 1 },
        { text: this.$t('approval.urgent'), value: 2 },
        { text: this.$t('approval.important'), value: 3 },
      ],
      priceTypeOptions: [
        { text: this.$t('order.notSelected'), value: null },
        { text: '合同价格', value: '101' },
        { text: '区域价格', value: '102' },
      ],
      applicantOptions: [{ text: this.$t('order.noData'), value: null }], //申请人员选项
      clientOptions: [{ text: this.$t('order.noData'), value: null }], //授信客户选项
    };
  },
  onLoad(options) {
    this.form.flowId = options.flowId
    if (options.id) {
      this.isCheckView = true
      this.id = options.id
      this.getApprovalFlowInfo()
    } else {
      this.userInfo = uni.getStorageSync("userInfo");
      this.getOptions()
      this.getApprovalFlow()
    }

  },
  methods: {
    //获取详情
    getApprovalFlowInfo() {
      let encode = this.enCode[0].toUpperCase() + this.enCode.slice(1)
      getApprovalInfo(encode, this.id).then(res => {
        if (res.data.code == 200) {
          this.form = res.data.data
          let data = res.data.data
          this.textForm.flowUrgent = data.flowUrgent == 1 ? this.$t('approval.ordinary') : (data.flowUrgent == 2 ? this.$t('approval.urgent') : this.$t('approval.important')) //紧急程度
          this.textForm.priceType = data.priceType == '101' ? '合同价格' : '挂牌价格'
        }
      })
      getApprovalFlowInfo(this.id).then(res => {
        if (res.data.code == 200) {
          let flow = JSON.parse(res.data.data.flowTaskInfo.flowTemplateJson)
          this.flow = flow
          this.forFlowObj(flow)
          this.flowList.forEach((item, index) => {
            res.data.data.flowTaskOperatorRecordList.forEach(i => {
              if (i.nodeCode == item.nodeId) {
                item.time = i.handleTime || ''
                item.handleOpinion = i.handleOpinion || ''
                this.currentIndex = index
              }
            })
            res.data.data.flowTaskNodeList.forEach(i => {
              if (i.nodeCode == item.nodeId) {
                item.content = i.userName || item.content
              }
            })
          })
        }
      })
    },
    //提交审批
    submit(ref) {
      let _this = this
      this.$refs[ref].validate().then(() => {
        let key = this.enCode[0].toUpperCase() + this.enCode.slice(1)
        this.$refs.loadingToast.show({
          type: "loading",
          message: _this.$t('base.common.loading'),
          duration: '100000',
        })
        createApproval(key, this.form).then(res => {
          if (res.data.code == 200) {
            this.$refs.loadingToast.hide()
            uni.showModal({
              title: _this.$t('settings.tips'),
              content: _this.$t('approval.creditApprovalSuccess'),
              showCancel: false,
              success: ({ confirm, cancel }) => {
                if (confirm) {
                  uni.navigateBack({ delta: 1 })
                }
              }
            })
          } else {
            this.$refs.loadingToast.hide()
            uni.showModal({
              title: _this.$t('settings.tips'),
              content: res.data.msg || _this.$t('approval.creditApprovalFail'),
              showCancel: false,
            })
          }
        }).catch(res => {
          _this.$refs.loadingToast.hide()
          console.log("调用异常返回、", res);
        });
      })
    },
    //获取审批流程
    getApprovalFlow() {
      getApprovalFlow(this.form.flowId).then(res => {
        if (res.data.code == 200) {
          this.form.flowTitle = this.userInfo.username + '的' + res.data.data.fullName
          let flow = JSON.parse(res.data.data.flowTemplateJson)
          this.flow = flow
          console.log(this.flow);
          this.forFlowObj(flow)
        }
      })
    },
    toPage() {
      this.$refs.form1.validateField('priceType', (res) => {
        if (res.length) {
          uni.showToast({
            title: res[0].message,
            icon: 'none',
          })
        } else {
          uni.navigateTo({ url: `/subpages/approval/price?priceType=${this.form.priceType}` })
        }
      })
    },
    //获取选项
    getOptions() {
      //流程编码
      BillNumber(this.enCode, dayjs().format('YYYY-MM-DD')).then(res => {
        if (res.data.code == 0) {
          this.form.wfCode = res.data.msg
        }
      })
    },
    //确定选择
    onConfirm(value, kind) {
      console.log(value, kind, '-----------------');
      if (value.value) {
        this.form[kind] = value.value
        this.textForm[kind] = value.text
      } else {
        this.form[kind] = ''
        this.textForm[kind] = ''
      }
    },
    //根据条件重新设置流程
    resetFlow(value) {
      if (this.isCheckView) {
        return
      }
      if (this.formcondition[value]) {
        this.flowList = []
        if (this.form[value]) {
          this.forFlowObj(this.flow)
        }
      }
    },
    //选择调价日期
    onSetDateConfirm(date) {
      this.form.setDate = dayjs(date).format('YYYY-MM-DD');
      this.showSetDateCalendar = false;
    },
    //选项格式
    formatOption(data) {
      let arr = []
      data.forEach(item => {
        arr.push(
          {
            text: item.name || item.label,
            value: item.value || item.id || item.userId
          }
        )
      })
      if (arr.length) {
        arr.unshift({ text: this.$t('order.notSelected'), value: null })
      } else {
        arr.unshift({ text: this.$t('order.noData'), value: null })
      }
      return arr
    },
    //循环对象
    forFlowObj(flow) {
      this.flowList.push(
        {
          title: flow.properties.title,
          content: flow.content,
          nodeId: flow.nodeId,
          time: '',
          handleOpinion: "",
        }
      )
      if (flow.conditionNodes && flow.conditionNodes.length) {
        flow.conditionNodes.forEach(item => {
          let math = item.properties.conditions
          if (this.eval(math)) {
            this.flowList.push(
              {
                title: item.properties.title,
                content: item.content,
                nodeId: item.nodeId,
                time: '',
                handleOpinion: "",
              }
            )
            this.forFlowObj(item.childNode)
          }
        })
      }
      if (flow.childNode) {
        this.forFlowObj(flow.childNode)
      }
    },
    beginDateConfirm(time) {
      this.form.beginDate = dayjs(time.value).format('YYYY-MM-DD HH:mm:ss')
      this.showBeginDate = false
    },
    finishDateConfirm(time) {
      this.form.finishDate = dayjs(time.value).format('YYYY-MM-DD HH:mm:ss')
      this.showFinishDate = false
    },
    //显示选择
    showPopup(refs) {
      if (this.isCheckView) {
        return
      }
      this.$refs[refs].showPicker = true
    },
    //计算方法
    eval(conditions) {
      let boo = false
      let booList = []
      conditions.forEach((item, index) => {
        switch (item.symbol) {
          case '>=':
            booList.push(this.form[item.field] >= Number(item.filedValue))
            if (index != conditions.length - 1) {
              booList.push(item.logic)
            }
            break;
          case '>':
            booList.push(this.form[item.field] > Number(item.filedValue))
            if (index != conditions.length - 1) {
              booList.push(item.logic)
            }
            break;
          case '==':
            booList.push(this.form[item.field] == Number(item.filedValue))
            if (index != conditions.length - 1) {
              booList.push(item.logic)
            }
            break;
          case '<=':
            booList.push(this.form[item.field] <= Number(item.filedValue))
            if (index != conditions.length - 1) {
              booList.push(item.logic)
            }
            break;
          case '<':
            booList.push(this.form[item.field] < Number(item.filedValue))
            if (index != conditions.length - 1) {
              booList.push(item.logic)
            }
            break;
          case '<>':
            booList.push(this.form[item.field] != Number(item.filedValue))
            if (index != conditions.length - 1) {
              booList.push(item.logic)
            }
            break;
        }
        this.formcondition[item.field] = true
      })
      let booList2 = []
      if (booList.length > 1) {
        booList.forEach((item, index) => {
          if (index % 2 != 0) {
            switch (item) {
              case "&&":
                booList2.push(booList[index - 1] && booList[index + 1])
                break;
            }
          } else {
            if (booList[index + 1] != "&&" && booList[index - 1] != "&&") {
              booList2.push(item)
            }
          }
        })
      } else {
        boo = booList[0]
      }
      if (booList2.length > 1) {
        booList2.forEach(item => {
          if (item) {
            boo = true
          }
        })
      } else if (booList2.length == 1) {
        boo = booList2[0]
      }
      return boo
    },
  }
};
</script>

<style lang="scss" scoped>
@import '../../common/css/apply.scss';
</style>