<template>
  <a-modal :visible="true" title="订单" :width="800" :footer="null" @cancel="cancel">
    <div class="pt-4">
      <a-form
        class="vben-basic-form"
        :model="formState"
        name="basic"
        autocomplete="off"
        layout="vertical"
        @finish="submit"
      >
        <a-row :gutter="32" class="!m-0">
          <a-col :span="12">
            <a-form-item
              label="订单编号"
              name="OrderNum"
              :rules="[{ required: true, message: '请输入订单编号' }]"
            >
              <a-input v-model:value="formState.OrderNum" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="订单名称"
              name="OrderName"
              :rules="[{ required: true, message: '请输入订单名称' }]"
            >
              <a-input v-model:value="formState.OrderName" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="订单总金额"
              name="OrderPriceCount"
              :rules="[{ required: true, message: '请输入订单总金额' }]"
            >
              <a-input-number
                disabled
                style="width: 100%"
                v-model:value="formState.OrderPriceCount"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="订单负责人"
              name="OrderManager"
              :rules="[{ required: true, message: '请输入订单负责人' }]"
            >
              <a-input disabled v-model:value="data.userName" />
            </a-form-item>
          </a-col>
        </a-row>
        <div class="btn-box">
          <SelectGoods class="mr-4" @submit="addGoods" />
          <SelectUser
            class="select-box"
            width="auto"
            :selectedIds="[data.userID]"
            :multiple="false"
            @change="getRuleUserIds"
            @change-names="getRuleUserNames"
          >
            <a-button type="primary" class="!rounded"> 选择负责人 </a-button>
          </SelectUser>
        </div>
        <div :class="prefixCls">
          <a-table
            size="middle"
            :data-source="dataSource"
            :columns="columns"
            :pagination="{
              hideOnSinglePage: true,
            }"
          >
            <template #headerCell="{ column }">
              <div class="header-cell__custom-title">{{ column.title }}</div>
            </template>
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'ProductAmount'">
                <div class="editable-cell">
                  <a-input-number v-model:value="record.ProductAmount" @change="save(record)" />
                </div>
              </template>
              <template v-else-if="column.dataIndex === 'operation'">
                <a-popconfirm
                  v-if="dataSource.length"
                  title="确定删除?"
                  @confirm="onDelete(record.ProductID)"
                >
                  <a class="!text-[#FF5461]">删除</a>
                </a-popconfirm>
              </template>
            </template>
          </a-table>
        </div>
        <a-form-item>
          <div class="flex justify-end pr-4"
            ><a-button type="primary" html-type="submit" class="my-10px !rounded"
              >提交</a-button
            ></div
          >
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import type { PropType, Ref } from 'vue';
  import { SelectUser } from '/@/components/SelectOrganizational/index';
  import SelectGoods from './SelectGoods.vue';
  import { add, edit } from './api/index';
  import { notification } from 'ant-design-vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  const { prefixCls } = useDesign('basic-table');
  const emits = defineEmits(['cancel']);
  const props = defineProps({
    data: {
      type: Object as PropType<any>,
    },
  });
  const data = reactive({ key: '', userID: '', userName: '', OrderID: '' });
  const formState = reactive({
    OrderNum: '',
    OrderName: '',
    OrderManager: '',
    OrderPriceCount: 0,
  });
  interface DataItem {
    ProductID: string;
    key: string;
    ProductName: string;
    ProductUnitPrice: number;
    ProductAmount: number;
    ProductPriceCount: number;
  }
  const dataSource: Ref<DataItem[]> = ref([]);
  const columns = [
    {
      title: '商品名称',
      dataIndex: 'ProductName',
      align: 'center',
    },
    {
      title: '单价',
      dataIndex: 'ProductUnitPrice',
      align: 'center',
    },
    {
      title: '数量',
      dataIndex: 'ProductAmount',
      align: 'center',
    },
    {
      title: '合计',
      dataIndex: 'ProductPriceCount',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      align: 'center',
    },
  ];
  onMounted(() => {
    if (props.data.OrderID) {
      data.OrderID = props.data.OrderID;
      formState.OrderName = props.data.OrderName;
      formState.OrderNum = props.data.OrderNum;
      formState.OrderManager = props.data.OrderManager;
      data.userID = formState.OrderManager;
      data.userName = props.data.OrderManagerName;
      formState.OrderPriceCount = props.data.OrderPriceCount;
      if (props.data.OrderProduct.length > 0) {
        dataSource.value = props.data.OrderProduct;
      }
    }
  });
  const save = (item: DataItem) => {
    item.ProductPriceCount = item.ProductAmount * item.ProductUnitPrice;
    changeOrderPriceCount();
  };
  const onDelete = (key: string) => {
    dataSource.value = dataSource.value.filter((item) => item.ProductID !== key);
    changeOrderPriceCount();
  };
  function changeOrderPriceCount() {
    if (dataSource.value.length > 0) {
      formState.OrderPriceCount = dataSource.value.reduce(function (a, b) {
        return a + b.ProductPriceCount;
      }, 0);
    } else {
      formState.OrderPriceCount = 0;
    }
  }
  function getRuleUserIds(val) {
    data.userID = val[0];
    formState.OrderManager = val[0];
  }
  function getRuleUserNames(val) {
    data.userName = val;
  }
  function addGoods(list) {
    let demo = list.map((ele) => {
      ele['ProductPriceCount'] = 0;
      ele['ProductAmount'] = 0;
      return ele;
    });
    dataSource.value.push(...demo);
  }
  async function submit() {
    let res = false;
    if (data.OrderID) {
      let params = {
        ...formState,
        OrderID: data.OrderID,
        OrderProduct: dataSource.value,
      };
      try {
        res = await edit(params);
      } catch (error) {}
    } else {
      let params = {
        ...formState,
        OrderProduct: dataSource.value,
      };
      try {
        res = await add(params);
      } catch (error) {}
    }

    if (res) {
      notification.success({
        message: '提示',
        description: '添加成功',
      }); //提示消息
      cancel();
    } else {
      notification.error({
        message: '提示',
        description: '添加失败',
      }); //提示消息
    }
  }
  function cancel() {
    emits('cancel');
  }
</script>

<style scoped>
  .btn-box {
    display: flex;
    margin: 0 16px 10px;
    justify-content: flex-end;
  }
</style>
