<script setup lang="ts">
import { ElMessage } from "element-plus";
import { computed, ref, unref } from "vue";
import { order_columns, order_status } from "./configs";
import { INPUT_MAX_LENGTH } from "/@/utils/global";
import { useTask } from "/@/hooks/core"
import ChooseModal from "./choose-invoice-modal/index.vue"
import { httpInfo } from "/@/api/InvoiceSales/capitalClaim";
import { httpPayAdd } from "/@/api/InvoiceSales/capitalClaim";
import FundDetail from "/@/components/FundDetail/index.vue"
import SalesModal from "./sales-modal.vue"
import { useRouter } from "vue-router"

const props = defineProps<{ readonly?: boolean; }>();
const emit = defineEmits(["create-btn-click"]);

const visible = ref(false)
const router = useRouter()
const disabled = computed(() => !props.readonly);
const saleOrderList = ref<Array<Record<string, string>>>([]);
const formData = ref({ tradNo: '', orderArr: [] })

const isReset = ref(false)

const addTask = useTask({ success(){ 
  if(isReset.value){
    ElMessage.success('新建成功')
    formData.value = { tradNo: '', orderArr: [] }
    saleOrderList.value = []
    mapSequenceNoToWpayfee.value = {}
    detailTask.data = null
  } else {
    ElMessage.success('新建成功')
    router.push('/InvoiceSales/capitalPool') 
  }
} })

const rules = { 
  tradNo: [{ required: true, message: '请选择资金', trigger: 'change' }],
  orderArr: [{ required: true, message: '请选择关联订单' }]
 }

const detailTask = useTask({ initialData: null })
const mapSequenceNoToWpayfee = ref<Record<string, string>>({});
const saleModalRef = ref<InstanceType<typeof SalesModal>>(null);

function addSaleOrder(sales: Array<Record<string, string>>) {
  sales.forEach(sale => {
    const { sequenceNo, wpay_fee } = sale;
    if (!mapSequenceNoToWpayfee.value[sequenceNo]) {
      mapSequenceNoToWpayfee.value[sequenceNo] = wpay_fee;
      saleOrderList.value.push(sale);
    }
  });
}

function handleCreate(value) {
  isReset.value = value;

  const orderArr: any = [];
  const keys = Object.keys(mapSequenceNoToWpayfee.value);
  keys.forEach(sequenceNo => orderArr.push({ sequenceNo, trad_fee: mapSequenceNoToWpayfee.value[sequenceNo] }));
  
  if (orderArr.length === 0) { return ElMessage.error("请添加关联订单"); }
  
  const parameter = { tradNo: formData.value.tradNo, orderArr }
  addTask.run(httpPayAdd(parameter))
}

function handleDelete(sequenceNo: string) {
  delete mapSequenceNoToWpayfee.value[sequenceNo];
  saleOrderList.value = saleOrderList.value.filter(row => row.sequenceNo !== sequenceNo);
}


function handleChoose(row = ({} as any)){
  detailTask.run(httpInfo({ tradNo: row.tradNo }))
  formData.value.tradNo = row.tradNo
  saleOrderList.value = []
}
</script>

<template>
  <div class="flex flex-col" v-loading="addTask.loading">
    <ElForm :model="formData" :rules="rules">
      <ElFormItem label="资金编号"  v-loading="detailTask.loading" prop="tradNo">
        <ElInput 
          class="mb-[10px]" 
          :modelValue="formData.tradNo"
          @click="visible = true"
          placeholder="资金编号"
        />
        
        <FundDetail v-if="detailTask.data" :tradeInfo="detailTask.data"  />
      </ElFormItem>

      <ElFormItem>
        <template #label>
          <div class="flex">
            <span style="color:#f56c6c">*</span>
            <div style="margin-left:3px;font-weight: 600">关联订单</div>
          </div>
        </template>

        <div class="flex flex-col w-full">
          <div class="flex w-full justify-end mb-[10px]">
            <el-button
              style="width:40px"
              v-if="disabled"
              type="primary"
              size="small"
              @click="() => saleModalRef.onDisplay(unref(saleOrderList))"
            >
              添加
            </el-button>
          </div>
        
        <el-table :data="saleOrderList" size="small" border prop="orderArr">
          <el-table-column
            v-for="(col, index) in order_columns"
            :key="index"
            :label="col.label"
            :prop="col.prop"
            :width="col.width"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <el-input
                size="small"
                placeholder="此次认领金额"
                v-if="col.label === '此次认领'"
                v-model="mapSequenceNoToWpayfee[row.sequenceNo]"
                v-bind="INPUT_MAX_LENGTH"
              />
            
              <el-tag v-else-if="col.prop === 'status'">
                {{ order_status.find(p => String(row.status) === p.value)?.label }}
              </el-tag>
            </template>
          </el-table-column>
        
          <el-table-column label="操作" fixed="right">
            <template #="{ row }">
              <el-button type="danger" link @click="handleDelete(row.sequenceNo)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        </div>
      </ElFormItem>
    </ElForm>

    <div flex justify-end mt-3 v-if="disabled">
      <ElButton  @click="handleCreate(false)">
        保存并返回
       </ElButton>

      <ElButton type="primary" @click="handleCreate(true)">
        仅保存
       </ElButton>
    </div>


    <SalesModal
      :isCommon="detailTask.data && detailTask.data.trade_type == '1'"
      ref="saleModalRef"
      @saveClickButton="addSaleOrder" 
    />
    
    
    <ChooseModal
      v-model:visible="visible" 
      @submit="handleChoose" 
    />
  </div>
</template>
