<script setup lang="ts">
import { ElTable, ElMessage } from "element-plus";
import { reactive, ref, unref, onMounted } from "vue";
import { useAsync } from "/@/hooks/core/useAsync";
import { httpCgdList } from "/@/api/purchase/orderRecord";
import { selectOptions as _selectOptions } from "../_options";

import {
  send_status_list,
  cg_order_source_options,
  cg_order_type_options,
  sendStatusOptions
} from "/@/utils/status";

const emit = defineEmits(["selection"]);
const props = defineProps<{
  supplierNo?: string;
  companyNo?: string;
  isComon?:string;
}>();

const tableRef = ref<InstanceType<typeof ElTable>>(null);
const selections = ref<Array<any>>([]);

const options = [
  { value: '2', label:'总货款不为零' },
  { value: '1', label:'总货款为零' }
];
const {
  data: tableData,
  loading,
  run
} = useAsync({
  isList: true,
  success: _data => (pagination.total = _data.count)
});

const formData = ref<Record<string, any>>({
  timer: [],
  sequenceNo: "",
  goodNo: "",
  goodName: "",
  cgder: "",
  cxCode: "",
  sendstatus: "",
  cgdsource: "",
  cgdtype: "",
  code: "",
  qrdCode: "",
  total: '2'
});

const pagination = reactive({
  pageSize: 15,
  currentPage: 1,
  total: 0
});

async function handleSearch() {
  loading.value = true;
  const { companyNo, supplierNo } = props;
  const { currentPage: page, pageSize: size } = pagination;
  const { timer, ...restParams } = formData.value;

  const searchParams = {
    ...restParams,
    start: timer[0],
    end: timer[1],
    is_comon: props.isComon,
    status: "0",
    supplierNo,
    companyNo,
    page,
    size
  };

  run(httpCgdList(searchParams));
}

//重置搜索
function handleReset() {
  pagination.currentPage = 1;
  formData.value = {
    timer: [],
    sequenceNo: "",
    goodNo: "",
    goodName: "",
    cgder: "",
    cxCode: "",
    sendstatus: "",
    cgdsource: "",
    cgdtype: "",
    code: "",
    qrdCode: "",
    total: '2'
  };
  handleSearch();
}

//表格节点选中
function handleSelection(val: any) {
  selections.value = val;
}

//派发保存
function onSubmit() {
  const isHasCancelSend = selections.value.filter(({ cgd_status }) => String(cgd_status) === "0");
  if (isHasCancelSend.length !== 0) {
    ElMessage.warning("不能选择采购单状态为 '待与供应商确认' 的的采购单");
    return;
  }

  const zeros = selections.value.filter(({totalPrice}) => Number(totalPrice) === 0)
  if (zeros.length !== 0) {
    ElMessage.warning(`采购单${zeros.map(({sequenceNo}) => sequenceNo).join('、')}添加失败,总货款不能为0元`)
    return
   }


  emit("selection", unref(selections));
}

const handleSizeChange = () => {
  pagination.currentPage = 1;
  handleSearch();
};

onMounted(() => {
  handleSearch();
});
</script>

<template>
  <ElRow :gutter="5" mb-1>
    <ElCol :span="6">
      <ElDatePicker
        size="small"
        type="daterange"
        v-model="formData.timer"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD"
        style="width: 100%"
      />
    </ElCol>

    <ElCol :span="6">
      <ElInput
        size="small"
        placeholder="采购单编码"
        v-model="formData.sequenceNo"
      />
    </ElCol>

    <ElCol :span="6">
      <ElInput
        size="small"
        placeholder="采购主单编码"
        v-model="formData.cxCode"
      />
    </ElCol>

    <ElCol :span="6">
      <ElInput
        size="small"
        placeholder="销售订单编码"
        v-model="formData.qrdCode"
      />
    </ElCol>
  </ElRow>
  <ElRow :gutter="5" mb-2>
    <ElCol :span="6">
      <ElInput size="small" placeholder="商品编码" v-model="formData.goodNo" />
    </ElCol>

    <ElCol :span="6">
      <ElInput
        size="small"
        placeholder="商品名称"
        v-model="formData.goodName"
      />
    </ElCol>

    <ElCol :span="6">
      <ElInput size="small" placeholder="采购员名称" v-model="formData.cgder" />
    </ElCol>

    <ElCol :span="6">
      <ElSelect
        placeholder="发货状态"
        v-model="formData.sendstatus"
        size="small"
        clearable
        w-full
      >
        <ElOption
          v-for="status in send_status_list"
          :key="status.value"
          :label="status.label"
          :value="status.value"
        />
      </ElSelect>
    </ElCol>
  </ElRow>
  <ElRow mb-2>
    <div w-full flex justify-between>
      <ElCol :span="16" style="display: flex; gap: 10px">
        <ElSelect
          v-model="formData.cgdsource"
          size="small"
          placeholder="订单来源"
          clearable
          w-full
        >
          <ElOption
            v-for="c in cg_order_source_options"
            :key="c.value"
            :label="c.label"
            :value="c.value"
          />
        </ElSelect>

        <ElSelect
          v-model="formData.cgdtype"
          size="small"
          w-full
          placeholder="商品来源"
          clearable
        >
          <ElOption
            v-for="c in cg_order_type_options"
            :key="c.value"
            :label="c.label"
            :value="c.value"
          />
        </ElSelect>
      
        <ElSelect style="width:100%" size="small" placeholder="总货款是否为零" v-model="formData.total" disabled>
          <ElOption value="2" label="总货款不为零" />
          <ElOption value="1" label="总货款为零" />
        </ElSelect>
      </ElCol>

      <ElCol :span="3">
        <ElButton size="small" @click="handleSearch" type="primary"
          >搜索</ElButton
        >
        <ElButton size="small" @click="handleReset">重置</ElButton>
      </ElCol>
    </div>
  </ElRow>

  <ElTable
    ref="tableRef"
    size="small"
    :data="tableData"
    v-loading="loading"
    @selection-change="handleSelection"
    max-height="580px"
  >
    <ElTableColumn type="selection" fixed="left" align="center" width="40" />
    <ElTableColumn
      label="采购单编码"
      prop="sequenceNo"
      show-overflow-tooltip
      width="150"
    />
    <ElTableColumn
      label="销售订单编码"
      prop="qrdCode"
      show-overflow-tooltip
      width="150"
    />

    <ElTableColumn
      label="采购主单编码"
      prop="cxCode"
      show-overflow-tooltip
      width="150"
    />
    <ElTableColumn label="类目信息">
      <ElTableColumn 
           label="类目编码"
           show-overflow-tooltip
           width="120"
         >
           <template #default="{ row }">
             <span v-if="row.orderTax">
               {{ row.orderTax.cat_code }}
             </span>
           </template>
          </ElTableColumn>
        
         <ElTableColumn 
           label="货物和劳务名称"
           show-overflow-tooltip
           width="130"
         >
           <template #default="{ row }">
             <span v-if="row.orderTax">
               {{ row.orderTax.cat_name }}
             </span>
           </template>
         </ElTableColumn>

         <ElTableColumn 
           label="商品和服务分类简称"
           show-overflow-tooltip
           width="160"
         >
           <template #default="{ row }">
             <span v-if="row.orderTax">
               {{ row.orderTax.short_name }}
             </span>
           </template>
         </ElTableColumn>
       
         <ElTableColumn 
           label="开票商品名称"
           show-overflow-tooltip
           width="130"
         >
         <template #default="{ row }">
             <span v-if="row.orderTax">
               {{ row.orderTax.inv_good_name }}
             </span>
           </template>
        </ElTableColumn>
      
        <ElTableColumn
           label="开票税率"
           show-overflow-tooltip
           width="80"
         >
         <template #default="{ row }">
             <span v-if="row.orderTax">
               {{ row.orderTax.tax ?   row.orderTax.tax + '%' : '' }}
             </span>
           </template>
        </ElTableColumn>
      </ElTableColumn>

    <ElTableColumn label="采购单信息">
      <ElTableColumn
        label="供货商"
        prop="supplierName"
        width="160"
        show-overflow-tooltip
      >
        <template #="{ row }">
          <ElTooltip placement="left" :content="'供应商编码:' + row.supplierNo">
            <IconifyIconOffline class="inline-block mr-[2px] cursor-pointer" icon="information-line" />
          </ElTooltip>
          {{ row.supplierName }}
        </template>
      </ElTableColumn>


      <ElTableColumn
        label="支付方式"
        prop="pay_type"
        width="85"
        show-overflow-tooltip
      />
       <ElTableColumn
          v-if="!edit"
          label="采购单状态"
          prop="cgd_status"
          min-width="140"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <ElTag>{{
              sendStatusOptions.find(s => s.value === String(row.cgd_status))
                ?.label || "--"
            }}
            </ElTag>
          </template>
        </ElTableColumn>

      <ElTableColumn
        label="发货状态"
        prop="sendStatus"
        width="90"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <ElTag size="small">{{ send_status_list.find(s => s.value === String(row.sendStatus))?.label }}</ElTag>
        </template>
      </ElTableColumn>

      <ElTableColumn
        label="业务公司"
        prop="companyName"
        width="180"
        show-overflow-tooltip
      >
        <template #="{ row }">
          <ElTooltip placement="left" :content="'业务公司编码:' + row.companyNo">
            <IconifyIconOffline class="inline-block mr-[2px] cursor-pointer" icon="information-line" />
          </ElTooltip>
          {{ row.companyName }}
        </template>
      </ElTableColumn>

      <ElTableColumn
        label="订单来源"
        prop="cgdSource"
        width="100"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <ElTag size="small">
            {{
              cg_order_source_options.find(
                t => t.value === String(row.cgdSource)
              )?.label
            }}
          </ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn
        label="总货款"
        prop="totalPrice"
        width="80"
        show-overflow-tooltip
      />
    </ElTableColumn>
    <ElTableColumn label="商品信息">
      <ElTableColumn
        label="商品编码"
        prop="goodNo"
        width="150"
        show-overflow-tooltip
      />
      <ElTableColumn
        label="商品名称"
        prop="goodName"
        width="180"
        show-overflow-tooltip
      />
      <ElTableColumn
        label="商品来源"
        prop="cgdType"
        width="90"
        show-overflow-tooltip
      >
        <template #="{ row }">
          <ElTag size="small">
            {{
              cg_order_type_options.find(t => t.value === String(row.cgdType))
                ?.label
            }}
          </ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn
        label="商品数量"
        prop="goodNum"
        width="90"
        show-overflow-tooltip
      />
    </ElTableColumn>
    <ElTableColumn
      label="采购员"
      prop="ownerName"
      width="70"
      show-overflow-tooltip
    />
  </ElTable>

  <!-- 分页器  -->
  <div flex mt-2 justify-between>
    <ElPagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      :page-sizes="[15, 50, 100]"
      layout="sizes, prev, pager, next"
      @current-change="handleSearch"
      @size-change="() => handleSizeChange()"
    />
    <ElButton type="primary" @click="onSubmit">保存</ElButton>
  </div>
</template>

<style lang="scss" scoped>
::v-deep(.el-input__wrapper) {
  // box-shadow: none !important;
  box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color))
    inset !important;
}
</style>
