<template>
  <div>
    <vxe-modal :value="isShow" show-footer :z-index="zIndex" title="支付审批明细" show-zoom show-confirm-button transfer
      resize :width="defaultModalSize.width" :height="defaultModalSize.height" @input="e => $emit('update:isShow',e)">
      <div>
        <div style="display: flex;align-items: center;justify-content: space-between;">
          <div style="display: flex;align-items: center;">
            <div class="xy-table-item-label">
              <span style="color: red; font-weight: 600; padding-right: 4px">*</span>申请付款金额
            </div>
            <div class="xy-table-item-content xy-table-item-price">
              <el-input clearable type="number" placeholder="请填写付款金额" v-model="fundlogForm.applyMoney"
                style="width: 150px;margin-left:10px" />
            </div>
          </div>
          <div style="display: flex;align-items: center;">
            <div class="xy-table-item-label">
              <span style="color: red; font-weight: 600; padding-right: 4px">*</span>款项类型
            </div>
            <div style="display: flex;align-items: center;">
              <el-select placeholder="选择款项类型或直接录入其他类型" v-model="fundlogForm.type" style="width: 200px;margin-left:10px"
                filterable allow-create clearable popper-append-to-body>
                <el-option v-for="item in paymentType" :key="item" :label="item" :value="item">
                </el-option>
              </el-select>
            </div>
          </div>
          <div style="display: flex;align-items: center;">
            <div class="xy-table-item-label">
              <span style="color: red; font-weight: 600; padding-right: 4px">*</span>是否为最后一笔
            </div>
            <div class="xy-table-item-content" style="margin-left:10px">
              <el-switch v-model="fundlogForm.isLast" />
              <!--                       @change="toggleSelection"-->
            </div>
          </div>
        </div>

        <vxe-table ref="table" stripe style="margin-top: 10px" keep-source :column-config="{ resizable: true }"
          :print-config="{}" :export-config="{}" :expand-config="{
              accordion: true,
              padding: true,
            }" :checkbox-config="{
              reserve: true,
              highlight: true,
              range: true,
              checkMethod: ({ row }) => {
                return parseFloat(row.hasPayNum) < parseFloat(row.num)
              }
            }" :row-config="{ keyField: 'id' }" :custom-config="{ mode: 'popup' }" :data="list">
          <vxe-column type="checkbox" width="50" align="center"></vxe-column>
          <vxe-column title="本次报销数量" width="120" align="center" field="payNum">
            <template #default="{ row }">

              <vxe-number-input v-if="parseFloat(row.hasPayNum) < parseFloat(row.num)" v-model="row.payNum" placeholder="数量"></vxe-number-input>
              <div v-else>-</div>
            </template>
          </vxe-column>
          <vxe-column title="已报销数量" width="100" align="center" field="hasPayNum">
          </vxe-column>
          <vxe-column align="center" v-for="item in table_item" :title="item.label" :field="item.prop"></vxe-column>

        </vxe-table>
      </div>

      <template #footer>
        <div style="margin-top: 20px;display: flex;justify-content: center;">
          <el-button type="primary" size="small" @click="submit">发起支付审批 <i class="el-icon-arrow-right"></i> </el-button>
        </div>
      </template>
    </vxe-modal>
    <!-- <Modal
      :width="86"
      class-name="oa-modal"
      title="流程办理"
      fullscreen
      :mask-closable="false"
      v-model="isShowOaModal"
      footer-hide
    >
      <div style="width: 100%;height: 100%;">
        <iframe style="width: 100%;height: 100%;border-radius: 0 0 6px 6px;" :src="oaUrl" frameborder="0"></iframe>
      </div>
    </Modal> -->
  </div>
</template>

<script>
  import {
    view,
    fieldConfig
  } from '@/api/flow'
  import {
    getItems,
    detailContract,
    getFundLog
  } from '@/api/flow/pay'
  import {
    PopupManager
  } from 'element-ui/lib/utils/popup'
  import {
    defaultModalSize
  } from "@/settings";

  export default {
    props: {
      isShow: {
        type: Boolean,
        default: false,
        required: true
      },
    },
    data() {
      return {
        payId: '',
        defaultModalSize,
        zIndex: PopupManager.nextZIndex(),
        list: [],
        table_item: [],
        flowDetail: {},
        fundlogForm:{
          applyMoney:0,
          type:'',
          isLast:false,
        },
        paymentType: ["进度款", "结算款", "质保金"],
        oaUrl:'',
        isShowOaModal:false,
      }
    },
    methods: {
      async getConfig() {
        const loading = this.$loading({
          lock: true,
          text: "拼命加载中",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.8)",
        });
        try {
          const res = await view(this.payId);

          const {
            fields
          } = res?.customModel;
          this.flowDetail = res?.flow
          const {
            data
          } = res?.flow
          fields.forEach((field) => {
            if (field.type === 'relation') {
              // 增加 自己提交的数量 和 已提交的数量
              this.list = JSON.parse(data[field.name])
              this.list.map(item => {
                item.payNum = 0
                item.hasPayNum = 0
              })
              this.getItemNum(this.payId)
              this.getFieldConfig(field.sub_custom_model_id)
            }
          });
          console.log("this.list", this.list)
          loading.close();
        } catch (err) {
          console.error(err)
          this.$message.error("配置失败");
          loading.close();
        }
      },
      // 获取采购明细
      async getFieldConfig(id) {
        try {
          const res = await fieldConfig(id)
          console.log("res", res)
          const fields = res?.customModel?.fields
          fields.forEach((field) => {
            this.table_item.push({
              label: field.label,
              prop: field.name
            })
          });


        } catch (err) {
          console.error(err)
        }

      },
      // 获取已提交的物资数量
      async getItemNum(id) {
        try {
          const item = await getItems({
            flow_id: id
          })
          console.log("item",item)
          if(item.length>0){
            const itemMap = new Map();
            item.forEach(item => {
              itemMap.set(item.wuzicaigou_item_id, item.total_num);
            });
            // 遍历 list 数组，根据 id 从 Map 中获取 total_num 并赋值给 hasPayNum
            this.list.forEach(item => {
              if (itemMap.has(item.id)) {
                item.hasPayNum = itemMap.get(item.id);
              }
            });
          }
        } catch (err) {
          console.error(err)
        }
      },
      async submit() {
        try {
          if(!this.fundlogForm.applyMoney){
            this.$message({
              message: '请填写本次申请付款金额',
              duration: 2000,
              type: 'warning'
            })
            return
          }
          if(!this.fundlogForm.type){
            this.$message({
              message: '请选择款项类型',
              duration: 2000,
              type: 'warning'
            })
            return
          }
          const records = this.$refs.table.getCheckboxRecords()
          console.log("records", records)
          let count = 0
          let totalCount = 0
          if (records.length < 1) {
            this.$message({
              message: '请选择需要报销的明细',
              duration: 2000,
              type: 'warning'
            })
            return
          }
          records.map(item => {
            if (parseFloat(item.payNum) === 0 || parseFloat(item.payNum) > parseFloat(item.num)) {
              count++
            }
            if(parseFloat(item.payNum)+parseFloat(item.hasPayNum) > parseFloat(item.num)){
              totalCount++
            }
          })
          if (count > 0) {
            this.$message({
              message: '报销数量不能为0或报销数量大于总数量',
              duration: 2000,
              type: 'warning'
            })
            return
          }
          if (totalCount > 0) {
            this.$message({
              message: '本次报销数量大于剩余可报销数量',
              duration: 2000,
              type: 'warning'
            })
            return
          }
          //wuzicaigou_items 报销的物资明细数组
          let wuzicaigou_items = []
          let zhifutitle = ''
          records.map(item=>{
            wuzicaigou_items.push({
              flow_id:this.payId,
              wuzicaigou_id:item.belongs_id,
              wuzicaigou_item_id:item.id,
              name:item.pinminghuofuwuxuqiu,
              num:item.payNum,
              total:item.num
            })
            zhifutitle+= item.pinminghuofuwuxuqiu+'X'+item.payNum+','
          })

          // 跳转到支付审批流程
          let payments = [];
          const actNumsTotal = () => {
            return payments.reduce((pre, cur) => {
              return pre + (!!Number(cur.act_money) ? Number(cur.act_money) : 0);
            }, 0);
          };
          let contract;
          if (this.flowDetail.out_contract_id) {
            contract = await detailContract({
              id: this.flowDetail.out_contract_id
            });
          }

          payments =
            (
              await getFundLog({
                contract_id: this.flowDetail.out_contract_id,
                show_type: 1
              })
            )?.data || [];
            // 付款登记的字段
            zhifutitle = zhifutitle.slice(0,-1)
            zhifutitle += "（"+this.flowDetail.title+'）'
            let baseInfo = {
              "oaUrl": contract?.number,
              "zhifutitle": zhifutitle,
// ?contract?.name
              "contract_id":contract.id,
              "type":this.fundlogForm.type,
              "is_end":this.fundlogForm.isLast ? 1 : 0,
              "amt": this.fundlogForm.applyMoney,
              // out_pay_id: row?.id,
              "xiangxishuoming": zhifutitle,
              "yifujine": actNumsTotal(),
              "xiangmuzonge": contract.money,
              "zhifucishu": contract?.sign_plan?.length,
              "cishu": payments.length,

              "liezhiqudao": contract?.plans.map(i => i.name)?.toString(),
              "contractno": contract?.number,
              "guanlianliucheng": contract?.contract_flow_links?.map(i => i.flow_id)?.toString(),
              "wuzicaigou_items":wuzicaigou_items
            };
            console.log(baseInfo,baseInfo)
            let url = `/flow/create?&module_name=oa&isSinglePage=1&module_id=75&default_json=${window.encodeURIComponent(JSON.stringify(baseInfo))}`;
            this.$router.push(
              url
            );
            // this.oaUrl = url;
            // this.isShowOaModal = true;
            this.$emit('update:isShow',false)
        } catch (err) {
          console.error(err)
        }
      }
    },
    computed: {},
    watch: {
      isShow(newVal) {
        if (newVal) {
          this.zIndex = PopupManager.nextZIndex()

          if (this.payId) {
            this.getConfig()

          }
        } else {
          this.list = []
          this.payId = ''
          this.oaUrl = ''
          this.isShowOaModal = false
          this.table_item = []
          this.flowDetail = {}
          this.fundlogForm = {
            applyMoney:0,
            type:'',
            isLast:false,
          }
          this.$refs.table.clearCheckboxRow()
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  ::v-deep .el-checkbox-group {
    font-size: inherit;
  }
</style>
