<script setup lang="ts">
import { send_status_list, useTypeOptions, xs_order_source_options, xs_order_type_options } from "/@/utils/status";
import { httpSaleList } from "/@/api/InvoiceSales/capitalClaim";
import { sale_type, sale_columns } from "./configs";
import { ElCol, ElMessage, ElTable } from "element-plus";
import { onMounted, ref, unref, computed, reactive } from "vue";
import { useAsync } from "/@/hooks";

import { useCompany } from "/@/hooks/core/useCompany";
import { DateRange } from "/@/components/BasicForm";

const props = defineProps<{ isCommon: boolean }>()


const visible = ref(false);
const emit = defineEmits(["save-click-button"]);

const parameter = reactive({
  value: '',
  key: 'cxCode'
})

const data = ref<Record<string, any>>({
  timer: [],
  poCode: '',
  goodNo: '',
  goodName: '',
  tag_id: '',
  cat_status: '',
  inv_status: '',
  sendstatus: '',
  sequenceNo: "",
  qrdtype: "",
  qrdsource: "",
  customer: "",
  platName: "",
  cxCode: "",
  platform_type: "1"
});

const { currentCompany } = useCompany();
const tableRef = ref<InstanceType<typeof ElTable>>(null);
const selectSaleOrder = ref<Array<Record<string, string>>>([]);


const title = computed(() => props.isCommon ? '通用订单' : '销售订单')

const initalPagination = {
  pageSize: 15,
  currentPage: 1,
  total: 0
};

const {
  loading,
  run: salelistRun,
  data: saleOrderList,
  pagination
} = useAsync<Array<Record<string, string>>>({
  initalData: [],
  isList: true,
  initalPagination
});

const handleSelectChange = values => (selectSaleOrder.value = values);

const requestSalelist = () => {
  const { currentPage: page, pageSize: size } = pagination;
  const { timer, ...rest } = data.value;
  salelistRun(
    httpSaleList({
      companyNo: currentCompany.value.companyNo,
      ...( props.isCommon ? { customerNo: 'GS2404151642335170' } : {}),
      pay_status: "0",
      start: timer[0],
      end: timer[1],
      status: '3',
      is_comon: props.isCommon ? '1' : '0',
      size,
      page,
      ...rest,
      [parameter.key]: parameter.value
    })
  );
};

function handleSave() {
  const wpayZero = selectSaleOrder.value.filter(({wpay_fee}) => Number(wpay_fee) === 0)
  if(wpayZero.length !== 0){
    ElMessage.warning('添加失败,订单 ' + wpayZero.map(({sequenceNo}) => sequenceNo).join('、') + ' 未付款金额为0')
    return
  }

  emit("save-click-button", unref(selectSaleOrder));
  visible.value = false;
}

const search = (isReset?: boolean) => {
  pagination.currentPage = 1;
  if (isReset) {
    data.value = {
      timer: [],
      poCode: '',
      goodNo: '',
      goodName: '',
      tag_id: '',
      cat_status: '',
      inv_status: '',
      sendstatus: '',
      sequenceNo: "",
      qrdtype: "",
      qrdsource: "",
      customer: "",
      platName: "",
      cxCode: "",
      platform_type: "1"
    };

   
    parameter.key = 'sequenceNo'
    parameter.value = ''
  }
  requestSalelist();
};

function handleSizeChange() {
  pagination.currentPage = 1;
  requestSalelist();
}

const inv_open_status = [
  { value: "1", label: "未开票" },
  { value: "2", label: "部分开票" },
  { value: "3", label: "已开票" }
];

const cat_status = [
  { value: "0", label: "待采购设置" },
  { value: "1", label: "待财务设置" },
  { value: "2", label: "已设置完成" }
];

const tag_type = [
  { value: "1", label: "开票标签" },
  { value: "2", label: "回款标签" },
  { value: "3", label: "开票或回款标签最少有一个" },
  { value: "4", label: "开票和回款标签同时有" }
];

const searchOptions = [
  { value: "cxCode", label: "销售订单主编码" },
  { value: "sequenceNo", label: "订单编码" },
  { value: "customerNo", label: "客户编码" },
  { value: "customer", label: "客户名称" },
  { value: "platName", label: "平台名称" },
  // { value: "poCode", label: "平台订单号" },
  { value: "department", label: "部门" },
  { value: "saler", label: "销售员" }
]

defineExpose({
  onDisplay: (_list: Array<Record<string, string>>) => {
    visible.value = true;
    requestSalelist();
  }
});

//初始化订单列表
onMounted(() => requestSalelist());
</script>

<template>
  <ElDialog :close-on-click-modal="false" :close-on-press-escape="false" @close="() => (selectSaleOrder = [])"
    v-model="visible" width="1040px" :title="title" top="10px" center>
    <ElRow :gutter="10" style="margin-bottom: 10px">
      <ElCol :span="8">
        <date-range size="small" v-model="data.timer" />
      </ElCol>

      <!-- <ElCol :span="8">
        <ElInput v-model="data.sequenceNo" placeholder="订单编码" size="small" />
      </ElCol> -->

      <ElCol :span="8">
        <ElSelect size="small" class="w-full" v-model="data.qrdsource" placeholder="订单来源" clearable>
          <ElOption v-for="opt in xs_order_source_options" :key="opt.value" v-bind="opt" />
        </ElSelect>
      </ElCol>

      <ElCol :span="8">
        <el-select class="w-full" size="small" clearable v-model="data.qrdtype" placeholder="商品类型">
          <el-option v-for="type in xs_order_type_options" :key="type.value" v-bind="type" />
        </el-select>
      </ElCol>
    </ElRow>

    <ElRow :gutter="10" style="margin-bottom: 10px">
      <el-col :span="8">
        <el-select placeholder="开票状态" size="small" style="width:100%" v-model="data.inv_status" clearable>
          <el-option v-for="opt in inv_open_status" v-bind="opt" />
        </el-select>
      </el-col>

      <el-col :span="8">
        <el-select placeholder="发货状态" size="small" style="width:100%" v-model="data.sendstatus" clearable>
          <el-option v-for="opt in send_status_list" v-bind="opt" />
        </el-select>
      </el-col>

      <el-col :span="8">
        <el-select placeholder="类目设置状态" size="small" style="width:100%" v-model="data.cat_status" clearable>
          <el-option v-for="opt in cat_status" v-bind="opt" />
        </el-select>
      </el-col>


      <!-- <el-col :span="8">
        <el-input placeholder="客户名称" size="small" v-model="data.customer" />
      </el-col>
      <el-col :span="8">
        <el-input placeholder="平台名称" size="small" v-model="data.platName" />
      </el-col> -->
    </ElRow>

    <el-row :gutter="10">
      <el-col :span="8">
        <el-select placeholder="标签类型" size="small" style="width:100%" v-model="data.tag_id" clearable>
          <el-option v-for="opt in tag_type" v-bind="opt" />
        </el-select>
      </el-col>

      <el-col :span="8">
        <el-input size="small" placeholder="商品编码" v-model="data.goodNo" />
      </el-col>

      <el-col :span="8">
        <el-input size="small" placeholder="商品名称" v-model="data.goodName" />
      </el-col>





      <!-- <el-col :span="8">
        <el-input v-model="data.cxCode" placeholder="销售订单主编码" size="small" />
      </el-col> -->
    </el-row>

    <ElRow :gutter="10" style="margin-top: 10px">
      <el-col :span="8">
        <el-input size="small" placeholder="平台订单号" v-model="data.poCode" />
      </el-col>

      <el-col :span="8">
        <el-input size="small" v-model="parameter.value">
          <template #prepend>
            <el-select v-model="parameter.key" size="small" style="width: 120px">
              <el-option v-for="opt in searchOptions" v-bind="opt" />
            </el-select>
          </template>
        </el-input>
      </el-col>



      <el-col :span="8">
        <el-switch v-model="data.platform_type" size="small" active-text="toC" inactive-text="toB" active-value="2"
          inactive-value="1" />
      </el-col>
    </ElRow>


    <div flex gap-2 justify-end mb-1>
      <el-button size="small" type="primary" @click="() => search()">搜索</el-button>
      <el-button size="small" @click="() => search(true)">重置</el-button>
    </div>

    <el-table v-loading="loading" :data="saleOrderList" @selection-change="handleSelectChange" ref="tableRef" border
      size="small" row-key="sequenceNo" max-height="520px">
      <el-table-column v-for="(col, index) in sale_columns" :prop="col.field" :label="col.label" :key="index"
        :width="col.width + 'px'" :fixed="col.fixed" :type="col.type" show-overflow-tooltip>
        <template #default="{ row }">
          <el-tag v-if="col.field === 'qrdType'" size="small">
            {{
            xs_order_type_options.find(s => s.value === row.qrdType)?.label ||
            "--"
            }}
          </el-tag>

          <el-tag v-if="col.field === 'cat_status'" size="small">
            {{
            cat_status.find(s => s.value === row.cat_status)?.label ||
            "--"
            }}
          </el-tag>

          <el-tag v-if="col.field === 'inv_status'" size="small">
            {{
            inv_open_status.find(s => s.value === row.inv_status)?.label ||
            "--"
            }}
          </el-tag>

          <el-tag v-else-if="col.field === 'qrdSource'" size="small">
            {{
            xs_order_source_options.find(s => s.value === row.qrdSource)
            ?.label || "--"
            }}
          </el-tag>

          <el-tag v-else-if="col.field === 'sendStatus'">
            {{
            send_status_list.find(p => String(row.sendStatus) === p.value)
            ?.label
            }}
          </el-tag>

          <el-tag v-if="col.field === 'platform_type'" size="small">
            {{
            useTypeOptions.find(s => s.value === row.platform_type)?.label ||
            "--"
            }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <div flex justify-between mt-2>
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :total="pagination.total" :page-sizes="[15, 50, 100]" @size-change="handleSizeChange"
        layout="sizes, prev, pager, next" @current-change="requestSalelist" size="small" />

      <div>
        <el-button type="primary" @click="handleSave" size="small">保存</el-button>
        <el-button @click="() => (visible = false)" size="small">取消</el-button>
      </div>
    </div>
  </ElDialog>
</template>
