<script setup lang="ts">
import { ref, watch, computed } from "vue"
import { ElForm, ElMessage } from "element-plus";
import { initialState, rules } from "./../config/constants"
import { useCompany } from "/@/hooks/core/useCompany";
import RemoteSelect from "/@/components/RemoteSelect";
import { httpGetSupplier } from "/@/api/user";
import { httpAdd } from "/@/api/postSupplierOrder/sendOrderRecord";
import { useAsync } from "/@/hooks";
import Modal from "./modal.vue"
import { useRouter } from "vue-router";
import { addition } from "/@/utils/calc";


const sendOrders = ref([]);
const { currentCompany } = useCompany();
const formData = ref({ ...initialState() });
const modalRef = ref<InstanceType<typeof Modal> | null>(null)
const formRef = ref<InstanceType<typeof ElForm> | null>(null)

const { push } = useRouter();

const { run, loading } = useAsync({
  success: () => push("/postSupplierOrder/postSupplierOrderCollection?tab=sendOrderRecord_collection")
});



const getLabel = company => {
  const { code, name, type } = company;
  const isCompany = type === "3" || type === "业务公司";
  const suffix = isCompany ? "(已升级为业务公司)" : "";
  return code + " / " + name + suffix;
};


function openModal(){
  if (!formData.value.companyNo || !formData.value.supplierNo) {
    ElMessage.warning('请选择买方公司和卖方公司')
    return
   }

  modalRef.value?.open();
}


// 添加发货运单
function add(orders) {
  const { sids } = formData.value;
  orders.forEach(order => {
    if (sids.includes(order.id)) return;
    formData.value.sids.push(order.id);
    sendOrders.value.push(order);
  })

  formRef.value?.validateField("sids");
}

// 删除发货运单
function deleteSendOrder(order) { 
  const index = sendOrders.value.findIndex(item => item.id === order.id);
  formData.value.sids.splice(index, 1);
  sendOrders.value.splice(index, 1);
  formRef.value?.validateField("sids");
}

async function confirm() { 
  try {
    await formRef.value.validate();
    const { sids: cids } = formData.value;
    run(httpAdd({ cids }))
  }catch(err){
    console.log(err)
  }
}


const totalAmount = computed(() => {
  return sendOrders.value.reduce((prev, current) => {
    return  Number(addition(prev, current.post_fee)).toFixed(2)
  }, 0)
})

watch(() => currentCompany, () => { 
  formData.value.companyNo = currentCompany.value.companyNo;
}, {
  immediate: true,
  deep: true
})
</script>

<template>
  <ElForm :rules="rules" :model="formData" ref="formRef" v-loading="loading">
      <div flex gap-10>
        <ElFormItem label="业务公司" prop="companyNo">
          <el-input  
           disabled 
           style="width: 386px" 
           :value="currentCompany.companyName" 
           placeholder="请选择买方公司"
          />
        </ElFormItem>

        <ElFormItem label="物流供应商" prop="supplierNo">
          <RemoteSelect 
            v-model:value="formData.supplierNo" 
            :api="httpGetSupplier"
            style="width: 386px" 
            placeholder="请选择卖方公司" 
            request-prop="name" 
            response-label-prop="name" 
            response-val-prop="code"
            :disabled-value="currentCompany.companyNo" 
           :getLabel="getLabel" 
          />
        </ElFormItem>
      </div>

      <ElFormItem prop="sids" label="发货运单信息">
        <div class="w-full">
          <div class="flex justify-between w-full mb-[10px]">
            <ElTag type="warning">共计{{formData.sids.length}}个订单, 共计{{totalAmount}}元</ElTag> 
            <ElButton type="primary" @click="openModal">添加发货运单</ElButton>
          </div>

          <ElTable size="small" border :data="sendOrders" max-height="450px">
            <ElTableColumn type="index" label="序号" min-width="55" show-overflow-tooltip />
            <ElTableColumn prop="TrackCode" label="发货运单编号" min-width="150px" show-overflow-tooltip />
            <ElTableColumn prop="outChildCode" label="发货工单编号" min-width="160px" show-overflow-tooltip />
            <ElTableColumn prop="orderCode" label="销售订单编号" min-width="150px" show-overflow-tooltip />
            <ElTableColumn prop="companyName" label="业务公司" min-width="180px" show-overflow-tooltip />
            <ElTableColumn prop="supplierName" label="物流供应商" min-width="180px" show-overflow-tooltip />
            <ElTableColumn label="物流费用" min-width="100px" prop="post_fee" show-overflow-tooltip></ElTableColumn>
            <ElTableColumn label="备注" prop="remark" min-width="140px" show-overflow-tooltip />
            <ElTableColumn label="创建人" prop="apply_name" min-width="120px" show-overflow-tooltip/>
            <ElTableColumn label="创建时间" prop="create_time" min-width="140px" show-overflow-tooltip/>
            <ElTableColumn label="操作" width="65px" align="center" fixed="right">
              <template #default="{ row }">
                <el-button type="text" @click="deleteSendOrder(row)" size="small">删除</el-button>
              </template>
            </ElTableColumn>
          </ElTable>
        </div>
     </ElFormItem>


     <div  class="flex justify-end">
      <ElButton type="primary" @click="confirm" :loading="loading">保存</ElButton>
     </div>
     
     <Modal 
      ref="modalRef" 
      @add="add" 
      :companyNo="formData.companyNo" 
      :supplierNo="formData.supplierNo" 
     />
  </ElForm>
</template>
