<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,
    regionalSpotManageGetAreaListApi,
    regionalSpotManageOpsAddProductApi,
  } from '/@/api/regionalSpotManage';
  import { getAuthCache } from '/@/utils/auth';
  const userInfo: any = getAuthCache('USER__INFO__');
  const ghsCode = userInfo.supplier.ghsCode;
  let searchBrand = ref('');
  let searchItemNo = ref('');
  let searchBrandList = ref<any[]>([]);
  const handleSearch = async (value) => {
    const res = await regionalSpotManageBrandListApi({ brand: value });
    if (res.code === 20000) {
      searchBrandList.value = res.data;
    } else {
      searchBrandList.value = [];
    }
  };
  const closeModal = () => {
    emit('close', false);
  };
  const leftData = ref<any[]>([]);
  const leftColumns = [
    {
      title: '商品名称',
      dataIndex: 'productName',
      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: true,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '30', '50', '100'],
    onChange: (current) => {
      pagination.value.current = current;
      getLeftData();
    },
    onShowSizeChange: (size) => {
      pagination.value.pageSize = size;
      getLeftData();
    },
  });
  const getLeftData = () => {
    leftData.value = [
      {
        productName: '测试产品1',
        brand: '测试品牌1',
        goodsNo: '213651',
        spec: '100ml',
        sysid: '1',
      },
      {
        productName: '测试产品2',
        brand: '测试品牌2',
        goodsNo: '213652',
        spec: '100ml',
        sysid: '2',
      },
      {
        productName: '测试产品3',
        brand: '测试品牌3',
        goodsNo: '213653',
        spec: '100ml',
        sysid: '3',
      },
      {
        productName: '测试产品4',
        brand: '测试品牌4',
        goodsNo: '213654',
        spec: '100ml',
        sysid: '4',
      },
      {
        productName: '测试产品5',
        brand: '测试品牌5',
        goodsNo: '213655',
        spec: '100ml',
        sysid: '5',
        choice: true,
      },
      {
        productName: '测试产品6',
        brand: '测试品牌6',
        goodsNo: '213656',
        spec: '100ml',
        sysid: '6',
        choice: true,
      },
    ];
    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];
    pagination.value.total = leftData.value.length;
  };
  let selectedRowKeys = ref<any[]>([]);
  let 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 = () => {
    console.log(selectedRows.value);
    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';
  };
  let loading = ref(false);
  let 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.code === 20000) {
      areaList.value = res.data;
    } else {
      areaList.value = [];
    }
    addressLoading.value = false;
  };
  // ==================================================
  const confirmLoading = ref(false);
  const addressVisible = ref(false);
  const checkboxValue = ref([]);
  const areaList = ref<any[]>([
    {
      id: '0',
      provinceId: '0',
      province: '北京市',
      cityId: 0,
      city: '市辖区',
      creator: '',
      creationTime: '',
    },
    {
      id: '1',
      provinceId: '1',
      province: '河北省',
      cityId: 1,
      city: '保定市',
      creator: '',
      creationTime: '',
    },
    {
      id: '2',
      provinceId: '2',
      province: '河北省',
      cityId: 2,
      city: '石家庄市',
      creator: '',
      creationTime: '',
    },
    {
      id: '3',
      provinceId: '3',
      province: '河北省',
      cityId: 3,
      city: '秦皇岛市',
      creator: '',
      creationTime: '',
    },
    {
      id: '4',
      provinceId: '4',
      province: '河北省',
      cityId: 3,
      city: '承德市',
      creator: '',
      creationTime: '',
    },
  ]);
  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.join;
    console.log(param.value);
    confirmLoading.value = true;
    const res = await regionalSpotManageOpsAddProductApi(param.value);
    if (res.code === 20000) {
      message.success('新增成功');
      addressVisibleClose();
      emit('close', false);
    } 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="false"
        :filter-option="false"
        :not-found-content="null"
        @search="handleSearch"
      >
        <a-select-option
          v-for="item in searchBrandList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
      <span style="margin-left: 15px">货号：</span>
      <Input
        v-model:value="searchItemNo"
        allow-clear
        placeholder="请输入货号"
        style="width: 200px"
      />
      <Button 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="loading"
          >
            <!-- <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"
          />
        </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.id">{{ 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>
