<template>
  <a-form-item-rest>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleAdd"> 添加 </a-button>
        <a-button type="primary" danger @click="handleDelete"> 移除</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'price'">
          <a-input-number
            v-model:value="record.price"
            :min="0"
            @change="handleNumberChange(record)"
          />
        </template>
        <template v-if="column.dataIndex === 'count'">
          <a-input-number
            v-model:value="record.count"
            :min="0"
            @change="handleNumberChange(record)"
          />
        </template>
        <template v-if="column.dataIndex === 'amount'">
          <a-input-number v-model:value="record.amount" disabled />
        </template>
        <template v-if="['payDate', 'pay_date'].includes(column.dataIndex)">
          <XjrDatePicker v-model:value="record[column.dataIndex]" format="YYYY-MM-DD" />
        </template>
        <template v-if="column.dataIndex === 'purpose'">
          <a-input v-model:value="record.purpose" />
        </template>
      </template>
    </BasicTable>
  </a-form-item-rest>
  <div class="table-bottom">
    <span>合计</span>
    <div>
      <span>
        总量：
        <span class="price">{{ total.countSum }}</span>
      </span>
      <span>
        总金额：
        <span class="price">{{ total.amountSum }}</span>
      </span>
    </div>
  </div>
  <a-form-item-rest>
    <SelectModal @register="registerSelectModal" @success="handleSuccess" />
  </a-form-item-rest>
</template>
<script lang="ts" setup>
  import { ref, unref, watch } from 'vue';
  import { useModal } from '/@/components/Modal';
  import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
  import SelectModal from '/@/views/erp/bom/components/SelectModal.vue';
  import { XjrDatePicker } from '/@/components/DatePicker';
  const props = defineProps({
    columns: {
      type: Array,
    },
    value: {
      type: Array,
    },
  });

  const total = ref({
    countSum: 0 as any,
    amountSum: 0 as any,
  });

  const emit = defineEmits(['update:value']);
  const isChange = ref(false);
  const customRow = (record) => {
    return {
      onClick: () => {
        let selectedRowKeys = [...getSelectRowKeys()];
        if (selectedRowKeys.indexOf(record.key) >= 0) {
          let index = selectedRowKeys.indexOf(record.key);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.key);
        }
        setSelectedRowKeys(selectedRowKeys);
      },
    };
  };

  watch(
    () => props.value,
    (val) => {
      setTableData(val || []);
      if (val && !isChange.value) {
        getDataSource()?.map((item) => {
          const price = item.price || 0;
          const count = item.count || 0;
          unref(total).countSum += count;
          unref(total).amountSum += count * price;
        });
        if (unref(total).amountSum) {
          unref(total).amountSum = unref(total).amountSum.toFixed(2);
        }
      }
    },
    {
      deep: true,
    },
  );

  const [registerTable, { setSelectedRowKeys, getSelectRowKeys, setTableData, getDataSource }] =
    useTable({
      title: '物品明细',
      columns: props.columns?.filter((x: any) => x.key !== 'action') as BasicColumn[],
      striped: false,
      pagination: false,
      rowSelection: {
        type: 'checkbox',
      },
      customRow,
    });

  const [registerSelectModal, { openModal }] = useModal();

  const handleNumberChange = (record) => {
    isChange.value = true;
    const price = record.price || 0;
    const count = record.count || 0;

    record.amount = price * count;

    handleTotalChange();
  };

  const handleAdd = () => {
    openModal(true, { type: 'checkbox' });
    isChange.value = true;
  };
  const handleSuccess = async (data) => {
    data.map((x) => {
      x.taxRate = 3;
      x.count = 0;
      x.unit_name = x.unitName;
      x.id = '';
    });
    setTableData([...getDataSource(), ...data]);
    emit('update:value', getDataSource());
  };

  const handleDelete = () => {
    const datasource = getDataSource().filter((x) => !getSelectRowKeys().includes(x.key));
    setTableData(datasource);
    handleTotalChange();
  };
  const handleTotalChange = () => {
    unref(total).countSum = 0;
    unref(total).amountSum = 0;
    getDataSource().map((item) => {
      const price = item.price || 0;
      const count = item.count || 0;
      unref(total).countSum += count;
      unref(total).amountSum += count * price;
    });
    unref(total).amountSum = unref(total).amountSum.toFixed(2);
  };
</script>
<style lang="less" scoped>
  .table-bottom {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #ddd;
    padding: 5px;

    & > div > span {
      margin-left: 40px;
    }
  }
</style>
