<script setup lang="ts">
import { ElForm, ElFormItem, ElButton, ElTable, ElTableColumn, ElMessage, ElTag, ElRow, ElCol, ElInput } from "element-plus"
import { ref, shallowReactive, onMounted, watch, shallowRef } from "vue";
import { httpCreate } from "/@/api/InvoiceSales/currentcyOrderRecord";
import { httpCompanylist } from "/@/api/netOrderEnter/netOrderEntry";
import { useCompany } from "/@/hooks/core/useCompany";
import RemoteSelect from "/@/components/RemoteSelect";
import { orderFormRules } from "../config/_options"
import { tyStatusOptions } from "/@/utils/status";
import OrderModal from "./order-modal.vue";
import { useAsync } from "/@/hooks/core";

const emit = defineEmits(["create"]);

const orderModalRef = ref<InstanceType<typeof OrderModal> | null>(null);
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const list = ref<Record<string, any>[]>([]);
const { currentCompany } = useCompany();
const platform_type = shallowRef("");

const formData = shallowReactive({ customerNo: "", companyNo: "" })
const { run } = useAsync({ success: () => emit('create') });

function handleList(val: Record<string, any>[]) {
  const sourceIds = list.value.map((item) => String(item.id));
  const uniqueList = val.filter(({ id }) => !sourceIds.includes(String(id)));
  list.value = [...list.value, ...uniqueList];
}

async function handleCreate() {
  if (list.value.length > 150) {
    ElMessage.warning('通用订单数量不能超过150条')
    return;
  }

  try {
    await formRef.value?.validate();
    if (list.value.length === 0) return ElMessage.warning('请选择通用订单');
    run(httpCreate({ common_ids: list.value.map(item => item.id) }))
  } catch (err) {
    console.log(err)
  }
}

function handleShowModal() {
  const { companyNo, customerNo } = formData;

  if (!customerNo) {
    ElMessage.warning("请选择买入方公司");
    return
  }

  if(customerNo === companyNo){
    ElMessage.warning("卖出方公司与买入方公司不能是同一家公司");
    return
  }

  orderModalRef.value?.onDisplay(customerNo, companyNo);
}

onMounted(() => {
  formData.companyNo = currentCompany.value.companyNo
  // formData.customerNo = 'GS2203161855277894'
});

watch(() => [formData.customerNo, formData.customerNo], () => list.value = []);
watch(() => platform_type.value, () => list.value = []);
</script>


<template>
  <ElForm :rules="orderFormRules" ref="formRef" :model="formData">
    <ElRow :gutter="10">
      <ElCol :span="12">
        <ElFormItem label="卖出方公司" prop="companyNo">
          <!-- 
              <RemoteSelect 
                  style="width: 100%" 
                  :api="httpGetSupplier" 
                  requestProp="name" 
                  responseLabel-prop="name"
                  responseValProp="code" 
                  placeholder="请选择卖方公司" 
                  v-model:value="formData.companyNo" 
                  :getLabel="getLabel"
                /> 
              -->
            <ElInput v-model="currentCompany.companyName" disabled></ElInput>
        </ElFormItem>
      </ElCol>

      <ElCol :span="12">
        <ElFormItem label="买入方公司" prop="customerNo">
          <!-- <ElInput modelValue="北京万宇恒通国际科贸有限公司" disabled></ElInput> -->
          <RemoteSelect
            ref="RemoteSelectRef"
            v-model="formData.customerNo"
            style="width: 100%"
            :api="httpCompanylist"
            requset-prop="name"
            response-label-prop="company_name"
            response-val-prop="companyNo"
            disabledValue="GS2404151642335170"
           />
        </ElFormItem>
      </ElCol>
    </ElRow>

    <ElFormItem class="be-current__item">
      <template #label>
        <div class="w-full flex justify-between">
          <div>
            <span style="color:red;margin-right:5px">*</span>
            <span>通用订单</span>
            <el-tag style="margin-left:10px" size="small">{{list.length}}/150</el-tag>
          </div>

          <div class="flex items-center">
            <p class="mr-[10px]">平台类型:</p>
            <el-switch class="mr-[10px]" v-model="platform_type" size="small" active-text="toC"
              inactive-text="toB" active-value="2" inactive-value="1" />
            <ElButton type="primary" size="small" @click="handleShowModal">添加通用订单</ElButton>
          </div>
        </div>
      </template>

      <ElTable border size="small" :data="list" class="mt-[10px]" :max-height="500">
        <ElTableColumn label="序号" type="index" fixed="left" align="center" />
        <ElTableColumn label="通用订单编号" min-width="160" prop="tyCode" show-overflow-tooltip />
        <ElTableColumn label="确认单编号" min-width="160" prop="orderCode" show-overflow-tooltip />
        <ElTableColumn label="销售订单主编号" min-width="160" prop="cxCode" show-overflow-tooltip />
        <ElTableColumn label="申请人" prop="apply_name" width="100px" show-overflow-tooltip />
        <ElTableColumn label="商品编号" min-width="160" prop="goodNo" show-overflow-tooltip />
        <ElTableColumn label="商品名称" min-width="160" prop="goodName" show-overflow-tooltip />
        <ElTableColumn label="类目编码" min-width="130" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.good ? scope.row.good.cgd_inv_cat_code : '' }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="货物和劳务名称" min-width="130" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.good ? scope.row.good.cgd_inv_cat_name : '' }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="开票商品名称" min-width="160" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.good ? scope.row.good.cgd_inv_good_name : '' }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="开票税率" min-width="80" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.good ? scope.row.good.cgd_inv_tax : '' }}
          </template>
        </ElTableColumn>

        <ElTableColumn label="卖出方公司" min-width="160" prop="companyName" show-overflow-tooltip />
        <ElTableColumn label="下单数量" width="80" prop="goodNum" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.qrd ? scope.row.qrd.goodNum : "" }}</template>
        </ElTableColumn>
        <ElTableColumn label="销售单价" width="80" prop="goodPrice" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.qrd ? scope.row.qrd.goodPrice : "" }}</template>
        </ElTableColumn>

        <ElTableColumn label="对账状态" width="80" prop="status" show-overflow-tooltip>
          <template #default="scope">
            <ElTag>
              {{ tyStatusOptions.find(c => c.value == scope.row.status)?.label || '--' }}
            </ElTag>
          </template>
        </ElTableColumn>

        <ElTableColumn label="税率" width="80" prop="goodPrice" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.qrd ? `${scope.row.qrd.tax}%` : "" }}</template>
        </ElTableColumn>

        <ElTableColumn label="下单时间" width="100" prop="addtime" show-overflow-tooltip />
        <ElTableColumn label="操作" fixed="right" width="60px">
          <template #default="scope">
            <ElButton size="small" type="primary" text @click="() => list.splice(scope.$index)">删除</ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
    </ElFormItem>

    <div class=" w-full flex justify-end">
      <ElButton type="primary" @click="handleCreate">保存</ElButton>
    </div>
  </ElForm>
  
  <OrderModal :platform_type="platform_type" ref="orderModalRef" @list="handleList" />
</template>


<style scoped lang="scss">
.be-current__item {
  display: block;

  ::v-deep(.el-form-item__label) {
    display: block;
  }
}
</style>
