<script setup lang="ts">
import { ref, computed, shallowRef} from "vue";
import { ElMessage } from "element-plus";
import PurchaseModal from "./purchase-modal.vue";

import EditModal from "./edit-modal.vue"

import {
  cg_order_type_options,
  cg_order_source_options,
  send_status_list,
  sendStatusOptions
} from "/@/utils/status";
import { Edit } from "vxe-table";

const emit = defineEmits(["push", "delete", "choose", "edit", "selectionChange", "batchSelection","batchCancelSelection"]);

const tableRef = ref<InstanceType<typeof ElTable> | null>(null);
const selected = ref([]);

const props = defineProps<{
  companyNo?: string;
  supplierNo?: string;
  purchaseOrders: any;
  readonly: boolean;
  isPurchPay?: boolean;
  isComon?:string;
  totalCommonPrice?: number
  totalCommonCount?: number
  edit?: boolean;
}>();

const PurchaseModalRef = ref<InstanceType<typeof PurchaseModal> | null>(null);
const editModalRef = ref<InstanceType<typeof EditModal> | null>(null);
const editIndex = shallowRef(-1);

function addition(arg1, arg2) {
  var r1, r2, m;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  return (arg1 * m + arg2 * m) / m;
}

//采购单个数
const total = computed(() => {
  return props.purchaseOrders.length;
});

const totalPrice = computed(() => {
  const { purchaseOrders } = props;
  const total = purchaseOrders.reduce(
    (prev, { totalPrice }) => addition(prev, totalPrice || 0),
    0
  );
  return Number(total).toFixed(2);
});

const onEdit = (index) => { 
  editIndex.value = index;
  editModalRef.value?.onDisplay(props.purchaseOrders[index]);
}

const onSave = (item) => { 
  emit('edit', item,editIndex.value);
  editIndex.value = -1;
}

const onSelectionChange = (val) => {
  selected.value = val; 
  // emit('selectionChange', selected.value.map(({ num, inv_fee, sequenceNo }) => ({ num, inv_fee, sequenceNo })));
}

function handleAddPurchase() {
  const { supplierNo, companyNo } = props;
  if (!supplierNo || !companyNo) {
    return ElMessage.warning("请选择供应商和业务公司");
  }
  PurchaseModalRef.value.onDisplay();
}

function handleSelectionOrder(isSelection = true) { 
  if (selected.value.length === 0) { 
    ElMessage.warning("请选择通用订单")
    return;
  }
  const ids = selected.value.map(({id}) => id);
  emit(isSelection ? 'batchSelection' : 'batchCancelSelection', ids);

  tableRef.value.clearSelection();
}

defineExpose({
  getOpenInvInfo:() => selected.value.map(({ num, inv_fee, sequenceNo }) => ({ num, inv_fee, sequenceNo }))
})
</script>

<template>
  <div>
    <div flex justify-between w-full mb-1>
      <ElTag 
        type="warning"
        v-if="!edit"
      >
        共计:{{ total }}个订单,共计 {{ totalPrice }} 元
      </ElTag >

      <!-- <ElButton 
        v-if="purchaseOrders.length !== 0 && edit" 
        type="primary"
        size="small"
        @click="onOpenInv"
        >开票申请
      </ElButton> -->

      <ElButton
        v-if="!readonly && !isPurchPay"
        type="primary"
        @click="handleAddPurchase"
        >添加采购单
      </ElButton>
    </div>

    <div class="mb-2" v-if="edit && purchaseOrders.length !== 0">
      <ElTag class="mr-[10px]">{{totalCommonCount}}/150 </ElTag>
      <ElTag class="mr-[10px]">{{totalCommonPrice}}元</ElTag>
      <ElButton @click="handleSelectionOrder">批量选中订单</ElButton>
      <ElButton @click="handleSelectionOrder(false)">批量取消选中订单</ElButton>
    </div>

    <ElTable
      ref="tableRef"
      row-key="id"
      size="small"
      :data="purchaseOrders"
      max-height="400"
      @selection-change="onSelectionChange"
    >
      <ElTableColumn fixed="left" type="selection" v-if="edit" />
      <ElTableColumn fixed="left" label="序号" type="index" v-if="edit" />     
      
      <ElTableColumn fixed="left" width="65px" label="是否选中" v-if="edit">
        <template #default="{ row }">
          <IconifyIconOffline v-if="row.isSelection" icon="success" style="color:#67C23A" />
        </template>
      </ElTableColumn>

      <ElTableColumn
        v-if="!edit"
        label="采购单编码"
        show-overflow-tooltip
        prop="sequenceNo"
        width="150"
      />

      
      <ElTableColumn
        label="销售订单编码"
        show-overflow-tooltip
        :prop="edit ? 'sequenceNo' : 'qrdCode'"
        width="150"
      />
      <ElTableColumn
        :label="edit ? '销售主单号' : '采购主单号'"
        show-overflow-tooltip
        prop="cxCode"
        width="150"
      />

      <ElTableColumn
        v-if="edit"
        label="采购单编码"
        show-overflow-tooltip
        prop="cgdNo"
        width="165"
      />

      <ElTableColumn label="采购单信息" v-if="!edit">
        <ElTableColumn
          v-if="!edit"
          label="供货商"
          prop="supplierName"
          min-width="160"
          show-overflow-tooltip
        />
        <ElTableColumn
          v-if="!readonly"
          label="支付方式"
          prop="pay_type"
          min-width="160"
          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
          v-if="!edit"
          label="销售单发货状态"
          prop="qrdSend"
          width="110"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <ElTag>{{
              send_status_list.find(s => s.value === String(row.qrdSend))
                ?.label || "--"
            }}</ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn
          v-if="!Edit"
          label="业务公司"
          prop="companyName"
          min-width="180"
          show-overflow-tooltip
        />
        <ElTableColumn
          v-if="!Edit"
          label="订单来源"
          prop="cgdSource"
          width="100"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <ElTag>
              {{
                cg_order_source_options.find(t => t.value === row.cgdSource)
                  ?.label
              }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn
          label="总货款"
          prop="totalPrice"
          width="80"
          show-overflow-tooltip
        />
        <ElTableColumn
          label="开票金额"
          prop="inv_fee"
          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="goodPrice"
          show-overflow-tooltip
        />
        <ElTableColumn
          v-if="!Edit"
          label="商品来源"
          prop="cgdType"
          width="90"
          show-overflow-tooltip
        >
          <template #="{ row }">
            <ElTag>
              {{
                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
        label="采购员"
        prop="ownerName"
        width="75"
        show-overflow-tooltip
      />

      <ElTableColumn label="税率" prop="tax" show-overflow-tooltip>
          <template #="{ row }"> {{ row.tax }}% </template>
        </ElTableColumn>
      </ElTableColumn>

        
      <template v-if="edit">
        <ElTableColumn
          label="未开票金额"
          prop="winv_fee"
          width="90"
          show-overflow-tooltip
        />

        <ElTableColumn
          label="本次开票金额"
          prop="inv_fee"
          width="110"
          show-overflow-tooltip
        />

       <ElTableColumn
          label="未开票数量"
          prop="winv_num"
          width="90"
          show-overflow-tooltip
        />

       <ElTableColumn
          label="本次开票数量"
          prop="num"
          width="110"
          show-overflow-tooltip
        />
      </template>

      <ElTableColumn label="操作" v-if="!readonly && !edit" fixed="right">
        <template #default="{ $index }">
          <ElButton link type="primary" @click="() => emit('delete', $index)">
            删除
          </ElButton>
        </template>
      </ElTableColumn>

      <ElTableColumn label="操作" width="65"  v-if="edit" fixed="right">
        <template #default="{ $index }">
          <ElButton link type="primary" @click="onEdit($index)">编辑</ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <PurchaseModal
      ref="PurchaseModalRef"
      :isComon="isComon"
      :companyNo="companyNo"
      :supplierNo="supplierNo"
      @pushOrder="orders => emit('push', orders)"
    />

    <EditModal
      ref="editModalRef"
      @save="onSave"
    />
  </div>
</template>
