<template>
  <div class="containe">
    <Search :navId="navId"></Search>
    <div class="contentWrap">
      <div class="top">
        <div class="title">{{ title }}</div>
        <div class="wrap">
          <Nav v-model:navList="navList" v-model:navActiveKey="navActiveKey" />
        </div>
      </div>
      <div class="info">
        <a-steps :current="1" size="small">
          <a-step title="我的购物车" />
          <a-step title="填写核对订单信息" />
          <a-step title="提交订单" />
        </a-steps>
        <div class="productList">
          <a-form
            :model="formData"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 14 }"
            autocomplete="off"
            ref="formRef"
            :rules="rulesRef"
          >
            <p>业务员信息</p>
            <a-form-item label="业务员" name="saleUserName">
              <a-input-group compact>
                <a-input v-model:value="formData.saleUserName" placeholder="业务员" style="width: 200px" disabled />
                <a-button type="primary" @click="handleShowSaleUser">选择业务员</a-button>
              </a-input-group>
            </a-form-item>
            <a-form-item label="开票公司" name="invoicingCompany">
              <a-input v-model:value="formData.invoicingCompany" disabled></a-input>
            </a-form-item>
            <a-form-item label="出货仓库" name="exWarehouse">
              <a-input v-model:value="formData.exWarehouse"></a-input>
            </a-form-item>
            <a-divider />
            <p>收货信息</p>
            <a-form-item label="发货方式" name="logisticsMode">
              <a-select
                ref="select"
                v-model:value="formData.logisticsMode"
                style="width: 300px"
                @change="handleChangeDespatch"
              >
                <a-select-option :value="item.value" v-for="item in logisticsEnumOptions" :key="item">{{
                  item.label
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <template v-if="formData.logisticsMode !== 'SELF'">
              <a-form-item label="收货地址" name="address">
                <a-input-group compact>
                  <a-input v-model:value="formData.address" placeholder="收货地址" style="width: 70%" disabled />
                  <a-button type="primary" @click="handleShowReceiver">查找</a-button>
                  <a-button>添加地址</a-button>
                </a-input-group>
              </a-form-item>
              <!-- <a-form-item label="收货地区" name="goodsCategoryList">
                <div class="area">
                  <a-input disabled placeholder="省"></a-input>
                  <a-form-item-rest><a-input disabled placeholder="市"></a-input></a-form-item-rest>
                </div>
              </a-form-item> -->
              <a-form-item label="收货人" name="receiveName">
                <a-input
                  v-model:value="formData.receiveName"
                  style="width: 200px"
                  placeholder="收货人"
                  disabled
                ></a-input>
              </a-form-item>
              <a-form-item label="联系电话" name="receivePhone">
                <a-input
                  v-model:value="formData.receivePhone"
                  style="width: 200px"
                  placeholder="联系电话"
                  disabled
                ></a-input>
              </a-form-item>
            </template>
            <a-form-item label="备注" name="remark">
              <a-input v-model:value="formData.remark"></a-input>
            </a-form-item>
          </a-form>
          <a-table
            :dataSource="productList"
            :columns="columns"
            :pagination="false"
            childrenColumnName="cartProductDetailList"
            rowKey="uuid"
            :scroll="{ y: 450 }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'type'">
                <span v-if="record.goodsType === 'PRODUCT'">产品</span>
                <span v-else-if="record.goodsType === 'KIT'">套件</span>
              </template>
            </template>
          </a-table>
          <div class="btnWrap">
            <a-button type="default" size="large" @click="handleGoBack">
              <template #icon>
                <left-outlined />
              </template>
              返回购物车
            </a-button>

            <div class="right">
              <span class="title"
                >已选数量：<span class="num">{{ productNum }}</span
                >件</span
              >
              <span class="title"
                >合计：<span class="num">{{ productNum }}</span
                >元</span
              >
              <a-button type="primary" size="large" @click="handleVerify" :disabled="productNum === 0"> 校验 </a-button>
              <a-button
                type="default"
                size="large"
                @click="handleSubmitOrder('TO_BE_USE')"
                :disabled="productNum === 0"
              >
                保存订单
              </a-button>
              <a-button
                type="primary"
                danger
                size="large"
                @click="handleSubmitOrder(undefined)"
                :disabled="productNum === 0"
              >
                提交订单
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <SaleUser ref="saleUserRef" @handleChange="handleChangeSaleUser" />
    <Receiver ref="receiverRef" @handleChange="handleChangeReceiver" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, reactive, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useGo } from '/@/hooks/web/usePage';
  import { useNavTree, useCartList } from '/@/hooks/myhooks/index';
  import { DataItem } from '/@/views/product/goods-category/type';
  import { cloneDeep, toNumber } from 'lodash';
  import { rulesRef } from './schema';
  import Search from '../components/search.vue';
  import Nav from '../components/nav.vue';
  import { logisticsEnumOptions } from '/@/views/order/enum';
  import { LeftOutlined } from '@ant-design/icons-vue';
  import SaleUser from '../components/saleUser.vue';
  import Receiver from '../components/receiver.vue';
  import { columns } from '../shoppingCart/schema';
  import * as BatchOrderApi from '/@/api/order/batchOrderApi';
  import { BatchOrder } from '/@/api/model/batchOrder';
  import { message } from 'ant-design-vue';
  import * as CartApi from '/@/api/order/cartApi';

  const go = useGo();
  const route = useRoute();
  const router = useRouter();
  const navTree = useNavTree();

  const saleUserRef = ref();
  const receiverRef = ref();
  const formRef = ref();

  const query = route.query;
  const navId = toNumber(query.nav); // 一级选择id
  const navList = ref<DataItem[]>([]); // 菜单树
  const navActiveKey = ref(navId); // 一级标签选择
  const title = ref(''); // 标题名称
  const productList = ref<any>([]);

  const formData = reactive<BatchOrder>({
    saleUserName: undefined,
    saleUserId: undefined,
    invoicingCompany: '王老吉',
    exWarehouse: '南京仓',
    logisticsMode: undefined,
    address: undefined,
    receiveName: undefined,
    receivePhone: undefined,
    remark: undefined,
  });

  const getGrandsonList = (arr: DataItem[]) => {
    arr.some((item) => {
      if (item.id === navId) {
        title.value = item.name;
        return true;
      }
    });
  };

  const getCartList = useCartList();

  // 选择发货方式
  const handleChangeDespatch = (val) => {
    console.log(val);
  };

  // 选择业务员
  const handleChangeSaleUser = (record) => {
    formData.saleUserName = record.realName;
    formData.saleUserId = record.id;
  };

  const handleShowSaleUser = () => {
    saleUserRef.value.visible = true;
  };

  const handleShowReceiver = () => {
    receiverRef.value.visible = true;
  };

  // 选择收件人
  const handleChangeReceiver = (record) => {
    formData.receiveName = record.receiveName;
    formData.receivePhone = record.receivePhone;
    formData.address = record.address;
  };

  const handleGoBack = () => {
    router.back();
  };

  // 校验
  const handleVerify = () => {};

  // 提交订单
  const handleSubmitOrder = (status: string | undefined) => {
    const batchOrder = cloneDeep(productList.value);
    batchOrder.forEach((item) => {
      item.batchOrderDetailProductDetailList = item.cartProductDetailList;
    });

    formRef.value.validate().then(() => {
      const api = status ? BatchOrderApi.save : BatchOrderApi.submit;

      api(Object.assign({ batchOrderDetailList: batchOrder }, formData)).then(() => {
        if (status) {
          message.success('保存成功');
        } else {
          message.success('提交成功');
        }
        CartApi.removeAll();
        go('/main/batch-order/order-list');
      });
    });
  };

  const productNum = computed(() => {
    let num = 0;
    productList.value.forEach((item) => {
      item.cartProductDetailList.forEach((product) => {
        num += product.quantity;
      });
    });
    return num;
  });

  onMounted(() => {
    navTree(navList, getGrandsonList, 'getGrandsonList');
    getCartList(productList);
  });
</script>

<style lang="less" scoped>
  p {
    margin: 0;
    padding: 0;
  }
  .containe {
    padding: 30px;
    .contentWrap {
      padding: 30px;
      background: #fff;
      border-radius: 10px;
      max-width: 1400px;
      min-width: 1200px;
      margin: 0 auto;

      .top {
        display: flex;
        justify-content: space-between;

        .title {
          width: 25%;
          background: #f7f9fa;
          color: #1890ff;
          border-radius: 10px;
          text-align: center;
          height: 50px;
          padding: 5px;
          line-height: 40px;
          font-size: 20px;
        }

        .wrap {
          width: 73%;
          margin: 0;
        }
      }

      .info {
        .ant-steps {
          width: 800px;
          margin: 20px auto;
        }

        .area {
          display: flex;
          justify-content: flex-start;

          input {
            width: 200px;
            margin-right: 10px;
          }
        }

        .btnWrap {
          background: #2d374b;
          height: 80px;
          line-height: 40px;
          padding: 20px 40px;
          border-radius: 0 0 10px 10px;
          display: flex;
          justify-content: space-between;

          .right {
            color: #fff;
            height: 40px;
            line-height: 40px;
            display: flex;
            align-content: center;

            .title {
              font-size: 20px;
              margin-right: 40px;

              .num {
                font-size: 30px;
                font-weight: 600;
                color: #ff0003;
              }
            }
            .ant-btn {
              margin-left: 10px;
            }
          }
        }
      }
    }
  }
</style>
