<script lang="ts" setup>
  import { ref, computed } from 'vue';
  import { message } from 'ant-design-vue';
  import { Input, Button } from 'ant-design-vue';
  import { RightOutlined, LeftOutlined } from '@ant-design/icons-vue';
  const emit = defineEmits(['close']);
  import {
    regionalSpotManageBrandListApi,
    regionalSpotManageProductListApi,
    regionalSpotManageGetAreaListApi,
    regionalSpotManageOpsAddProductApi,
  } from '/@/api/regionalSpotManage';
  import { getAuthCache } from '/@/utils/auth';
  const userInfo: any = getAuthCache('USER__INFO__');
  const ghsCode = userInfo.supplier.ghsCode;
  const searchBrand = ref('');
  const searchItemNo = ref('');
  const searchBrandList = ref<any[]>([]);
  const handleSearch = async (value) => {
    const res = await regionalSpotManageBrandListApi({ brand: value });
    if (res.success) {
      searchBrandList.value = res.data;
    } else {
      searchBrandList.value = [];
    }
  };
  const closeModal = () => {
    emit('close', false);
  };
  const leftLoading = ref(false);
  const leftData = ref<any[]>([]);
  const leftColumns = [
    {
      title: '商品名称',
      key: 'productName',
      width: '25%',
      align: 'center',
    },
    { title: '品牌', dataIndex: 'brand', key: 'brand', width: '25%', align: 'center' },
    { title: '货号', dataIndex: 'goodsNo', key: 'goodsNo', width: '20%', align: 'center' },
    { title: '规格', dataIndex: 'spec', key: 'spec', width: '20%', align: 'center' },
  ];
  const pagination = ref({
    size: 'small',
    pageSize: 10,
    current: 1,
    total: 0,
    showTotal: (total) => `共 ${total} 条`,
    hideOnSinglePage: false,
    showQuickJumper: false,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '30', '50', '100'],
    onChange: (current, size) => {
      pagination.value.current = current;
      pagination.value.pageSize = size;
      getLeftData();
    },
  });
  const reset = () => {
    searchBrand.value = '';
    searchItemNo.value = '';
    pagination.value.current = 1;
    getLeftData();
  };
  const getLeftData = async () => {
    const param = {
      pageIndex: pagination.value.current,
      pageSize: pagination.value.pageSize,
      ghsCode: ghsCode,
      productName: '',
      brand: searchBrand.value,
      goodsNo: searchItemNo.value,
    };
    leftLoading.value = true;
    const res = await regionalSpotManageProductListApi(param);
    if (res.success) {
      leftData.value = res.data;
      pagination.value.total = res.data[0].total;
    } else {
      leftData.value = [];
      pagination.value.total = 0;
    }
    leftLoading.value = false;
    if (rightData.value.length > 0) {
      for (let i = 0; i < rightData.value.length; i++) {
        if (
          leftData.value.findIndex(
            (v) =>
              v.brand + v.goodsNo + v.spec ===
              rightData.value[i].brand + rightData.value[i].goodsNo + rightData.value[i].spec,
          ) !== -1
        ) {
          leftData.value.find(
            (v) =>
              v.brand + v.goodsNo + v.spec ===
              rightData.value[i].brand + rightData.value[i].goodsNo + rightData.value[i].spec,
          ).choice = true;
        }
      }
    }
    leftData.value = [...leftData.value];
  };
  const selectedRowKeys = ref<any[]>([]);
  const selectedRows = ref<any[]>([]);
  const rowSelection = computed(() => {
    return {
      selectedRowKeys: selectedRowKeys.value,
      onChange: (RowKeys, Rows) => {
        selectedRowKeys.value = RowKeys;
        selectedRows.value = Rows;
      },
      getCheckboxProps: (record) => ({
        disabled: record.choice === true,
      }),
    };
  });
  const toRight = () => {
    let arr = JSON.parse(JSON.stringify(selectedRows.value));
    rightData.value = [...arr, ...rightData.value];
    for (let i = 0; i < selectedRows.value.length; i++) {
      if (
        leftData.value.findIndex(
          (v) =>
            v.brand + v.goodsNo + v.spec ===
            selectedRows.value[i].brand +
              selectedRows.value[i].goodsNo +
              selectedRows.value[i].spec,
        ) !== -1
      ) {
        leftData.value.find(
          (v) =>
            v.brand + v.goodsNo + v.spec ===
            selectedRows.value[i].brand +
              selectedRows.value[i].goodsNo +
              selectedRows.value[i].spec,
        ).choice = true;
      }
    }
    leftData.value = [...leftData.value];
    selectedRowKeys.value = [];
    selectedRows.value = [];
  };
  const rightData = ref<any[]>([]);
  const rightSelectedRowKeys = ref<any[]>([]);
  const rightSelectedRows = ref<any[]>([]);
  const rightRowSelection = computed(() => {
    return {
      selectedRowKeys: rightSelectedRowKeys.value,
      onChange: (RowKeys, Rows) => {
        rightSelectedRowKeys.value = RowKeys;
        rightSelectedRows.value = Rows;
      },
    };
  });
  const toLeft = () => {
    for (let i = 0; i < rightSelectedRows.value.length; i++) {
      if (
        leftData.value.findIndex(
          (v) =>
            v.brand + v.goodsNo + v.spec ===
            rightSelectedRows.value[i].brand +
              rightSelectedRows.value[i].goodsNo +
              rightSelectedRows.value[i].spec,
        ) !== -1
      ) {
        leftData.value.find(
          (v) =>
            v.brand + v.goodsNo + v.spec ===
            rightSelectedRows.value[i].brand +
              rightSelectedRows.value[i].goodsNo +
              rightSelectedRows.value[i].spec,
        ).choice = false;
        rightData.value.splice(
          rightData.value.findIndex(
            (v) =>
              v.brand + v.goodsNo + v.spec ==
              rightSelectedRows.value[i].brand +
                rightSelectedRows.value[i].goodsNo +
                rightSelectedRows.value[i].spec,
          ),
          1,
        );
      } else {
        rightData.value.splice(
          rightData.value.findIndex(
            (v) =>
              v.brand + v.goodsNo + v.spec ==
              rightSelectedRows.value[i].brand +
                rightSelectedRows.value[i].goodsNo +
                rightSelectedRows.value[i].spec,
          ),
          1,
        );
      }
    }
    leftData.value = [...leftData.value];
    rightData.value = [...rightData.value];
    rightSelectedRowKeys.value = [];
    rightSelectedRows.value = [];
  };
  const rowClassName = () => {
    return 'table-back';
  };
  const loading = ref(false);
  const addressLoading = ref(false);
  const goNext = async () => {
    if (!rightData.value.length) return message.error('请先选择商品');
    addressVisible.value = true;
    addressLoading.value = true;
    const res = await regionalSpotManageGetAreaListApi({});
    if (res.success) {
      areaList.value = res.data;
    } else {
      areaList.value = [];
    }
    addressLoading.value = false;
  };
  // ==================================================
  const confirmLoading = ref(false);
  const addressVisible = ref(false);
  const checkboxValue = ref([]);
  interface AreaIds {
    city?: string;
    cityId?: number;
    creationTime?: string;
    creator?: string;
    id?: number;
    province?: string;
    provinceId?: number;
  }
  const areaList = ref<AreaIds[]>([]);
  const handleCancel = () => {
    addressVisibleClose();
  };
  const goPrevious = () => {
    addressVisibleClose();
  };
  const addressVisibleClose = () => {
    addressVisible.value = false;
    checkboxValue.value = [];
  };
  const confirm = async () => {
    if (!checkboxValue.value.length) return message.error('请选择现货区域');
    const param = ref<{ [key: string]: any }>({
      products: [],
      areas: '',
    });
    param.value.products = rightData.value.map((v) => {
      return {
        goodsNo: v.goodsNo,
        brand: v.brand,
        spec: v.spec,
        ghscode: ghsCode,
      };
    });
    param.value.areas = checkboxValue.value;
    confirmLoading.value = true;
    const res = await regionalSpotManageOpsAddProductApi(param.value);
    if (res.success) {
      message.success('新增成功');
      addressVisibleClose();
      emit('close', false, 'refresh');
    } else {
      message.error(res.message);
    }
    confirmLoading.value = false;
  };
</script>

<template>
  <a-modal
    :visible="true"
    title="新增区域现货商品"
    :width="1200"
    @cancel="closeModal"
    :maskClosable="false"
    :keyboard="false"
  >
    <template #footer>
      <a-button key="back" @click="closeModal">取消</a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="goNext">下一步</a-button>
    </template>
    <div>
      <span>品牌名称：</span>
      <a-select
        v-model:value="searchBrand"
        show-search
        placeholder="请输入品牌名称"
        style="width: 200px"
        :default-active-first-option="false"
        :show-arrow="true"
        :filter-option="false"
        :not-found-content="null"
        @search="handleSearch"
      >
        <a-select-option
          v-for="item in searchBrandList"
          :key="item.brand"
          :label="item.brand"
          :value="item.brand"
        >
          {{ item.brand }}
        </a-select-option>
      </a-select>
      <span style="margin-left: 15px">货号：</span>
      <Input
        v-model:value="searchItemNo"
        allow-clear
        placeholder="请输入货号"
        style="width: 200px"
      />
      <Button @click="reset" style="margin-left: 10px">重置</Button>
      <Button @click="getLeftData" type="primary" style="margin-left: 10px">查询</Button>
    </div>
    <div class="main">
      <div class="left">
        <div class="header">
          <div>筛选结果商品</div>
          <span>{{ selectedRowKeys.length }}/{{ pagination.total }}</span>
        </div>
        <div class="table">
          <a-table
            bordered
            :data-source="leftData"
            :columns="leftColumns"
            :pagination="pagination"
            :row-selection="rowSelection"
            :rowKey="(record) => record.brand + record.goodsNo + record.spec"
            :scroll="{ x: false, y: 280 }"
            :rowClassName="rowClassName"
            :loading="leftLoading"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'productName'">
                <span>{{ record.chineseName ? record.chineseName : record.englishName }}</span>
              </template>
            </template>
          </a-table>
        </div>
      </div>
      <div class="operate">
        <div style="margin-top: 200px; display: flex">
          <a-button
            @click="toLeft"
            type="primary"
            :disabled="rightSelectedRowKeys.length === 0"
            style="display: block; margin-bottom: 10px; margin-right: 10px"
          >
            <template #icon>
              <LeftOutlined />
            </template>
          </a-button>
          <a-button
            @click="toRight"
            type="primary"
            style="display: block"
            :disabled="selectedRowKeys.length === 0"
          >
            <template #icon>
              <RightOutlined />
            </template>
          </a-button>
        </div>
      </div>
      <div class="right">
        <div class="header">
          <div>被选中商品</div>
          <span>{{ rightSelectedRowKeys.length }}/{{ rightData.length }}</span>
        </div>
        <div class="table">
          <a-table
            :data-source="rightData"
            :columns="leftColumns"
            :pagination="false"
            :rowKey="(record) => record.brand + record.goodsNo + record.spec"
            :scroll="{ x: false, y: 280 }"
            :rowClassName="rowClassName"
            :row-selection="rightRowSelection"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'productName'">
                <span>{{ record.chineseName ? record.chineseName : record.englishName }}</span>
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </div>
  </a-modal>
  <a-modal
    v-model:visible="addressVisible"
    title="新增区域现货商品"
    @cancel="handleCancel"
    @ok="confirm"
    :width="1200"
    :maskClosable="false"
    :keyboard="false"
  >
    <template #footer>
      <a-button :loading="confirmLoading" @click="handleCancel">取消</a-button>
      <a-button :loading="confirmLoading" @click="goPrevious">上一步</a-button>
      <a-button type="primary" :loading="confirmLoading" @click="confirm">提交</a-button>
    </template>
    <a-alert type="warning">
      <template #message>
        <span style="color: red">特别提醒：</span
        >若商品之前已设置现货区域，则本次设置为在之前设置基础上新增。例如，原来商品设置为
        北京市-直辖市；天津市-直辖市。本次设置为，北京市-直辖市；四川省-成都市。提交后，商品现货区域将更新为
        北京市-直辖市；天津市-直辖市；四川省-成都市。
      </template>
    </a-alert>
    <a-spin v-if="addressLoading" style="height: 150px; width: 100%; line-height: 150px" />
    <div v-else>
      <p style="margin-top: 15px">选择现货区域：</p>
      <a-checkbox-group v-model:value="checkboxValue" style="width: 100%">
        <a-row>
          <a-col :span="6" v-for="(item, index) in areaList" :key="index">
            <a-checkbox :value="item.cityId">{{ item.province }}-{{ item.city }}</a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </div>
  </a-modal>
</template>

<style lang="less" scoped>
  .main {
    display: flex;
    justify-content: space-around;
    width: 100%;
    margin-top: 15px;
    .left {
      width: 45%;
      border: 1px solid #ddd;
      height: 450px;
      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 10px;
        height: 60px;
        background: #f3f6f9;
      }
    }
    .right {
      width: 45%;
      border: 1px solid #ddd;
      height: 450px;
      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 10px;
        height: 60px;
        background: #f3f6f9;
      }
    }
    .operate {
      width: 10%;
      height: 450px;
      display: flex;
      justify-content: center;
      align-content: center;
    }
  }
  /deep/.table-back {
    background-color: #fff;
  }
</style>
