<template>
  <div class="complaints-page">
    <a-card class="search-form">
      <a-button type="primary" style="margin: 0 5px" @click="addBtn">新增区域</a-button>
      <a-table
        :columns="columns"
        :dataSource="tableData"
        :scroll="{ x: 'max-content' }"
        :loading="tableLoading"
        rowKey="id"
        :pagination="false"
      >
        <template #platList="{ record }">
          <p v-for="item in record.platList" :key="item.platCode">{{ item.platName }}</p>
        </template>
        <template #action="{ record }">
          <a-button type="link" @click="manageBtn(record)">管理客户平台</a-button>
        </template>
      </a-table>
      <a-pagination
        style="text-align: right; margin-top: 10px"
        v-model:current="page"
        simple
        :total="total"
      >
        <template #itemRender="{ type, originalElement }">
          <a-button size="small" v-if="type === 'prev'">上一页</a-button>
          <a-button size="small" v-else-if="type === 'next'">下一页</a-button>
          <component :is="originalElement" v-else />
        </template>
      </a-pagination>
    </a-card>
    <a-modal
      v-model:visible="visible"
      okText="提交"
      title="新增区域"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="cancelHandle"
    >
      <div>
        <a-form layout="inline" :model="form">
          <a-form-item label="">
            <a-select
              v-model:value="form.province"
              show-search
              placeholder="请选择省"
              style="width: 200px"
              @change="onProvinceChange"
              :filter-option="filterOption"
            >
              <a-select-option v-for="item in provinceOptions" :key="item.name" :value="item.code"
                >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="">
            <a-select
              :disabled="cityDisadble"
              v-model:value="form.cityName"
              show-search
              placeholder="请选择市"
              style="width: 200px"
              :filter-option="filterOption"
            >
              <a-select-option v-for="item in cityOptions" :key="item.name" :value="item.code">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <a-modal
      v-model:visible="manageVisible"
      title="管理客户平台"
      okText="提交"
      :confirmLoading="manageConfirmLoading"
      @ok="manegeHandleOk"
      @cancel="manegecancelHandle"
    >
      <div v-loading="modalLoading">
        <p style="margin: 10px; font-weight: bold"
          >{{ currentItem.province }}{{ currentItem.cityName }}</p
        >
        <!-- 人工管理 -->
        <div class="box">
          <div class="title">人工管理</div>
          <div class="innerbox">
            <div style="border: 1px solid #ddd" v-for="item in peopleData" :key="item.id">
              <p>{{ item.platName }}</p>
              <a-button
                class="icon"
                type="link"
                @click="removePeoplePlat(item)"
                :icon="h(DeleteOutlined)"
              />
              <!-- <Icon class="icon" icon="delete"></Icon> -->
            </div>
            <div style="border: 1px solid #ddd" v-for="(item, index) in addPlatList" :key="index">
              <a-select
                class="addPlatSelect"
                v-model:value="item.platCode"
                show-search
                style="width: 100%"
                placeholder="请选择平台"
                :filter-option="filterOptionPlat"
              >
                <a-select-option v-for="i in platOptions" :key="i.platName" :value="i.platCode">{{
                  i.platName
                }}</a-select-option>
              </a-select>
              <a-button
                class="icon"
                type="link"
                @click="removePlatBtn(index)"
                :icon="h(DeleteOutlined)"
              />
            </div>
            <div style="text-align: center">
              <a-button @click="addPlatBtn" :icon="h(PlusOutlined)">添加行</a-button>
            </div>
          </div>
        </div>
        <!-- 系统管理 -->
        <div class="box">
          <div class="title">系统管理</div>
          <div class="innerbox" v-if="rootData.length">
            <div style="border: 1px solid #ddd" v-for="item in rootData" :key="item.id">{{
              item.platName
            }}</div>
          </div>
          <div class="innerbox" v-else>
            <div style="text-align: center; border: 1px solid #ddd">暂无数据</div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import { Modal } from 'ant-design-vue';
  import { ref, h, onMounted } from 'vue';
  // import { useRouter } from 'vue-router';
  import {
    getScAreaListApi,
    dictRegionListApi,
    addScAreaApi,
    getPlatListApi,
    removeScAreaPlatformApi,
    addScAreaPlatformApi,
    getPlatListAllApi,
  } from '/@/api/super/regionalSpotManage/index';
  import moment from 'moment';
  import { message } from 'ant-design-vue';
  // const router = useRouter();
  const tableData = ref<any[]>([]);
  const tableLoading = ref<any>(false);
  const visible = ref<any>(false); //
  const page = ref<any>(1); //
  const pageSize = ref<any>(10); //
  const total = ref<any>(1); //
  const confirmLoading = ref<any>(false); //
  const cityDisadble = ref<any>(true); //
  const form = ref<any>({
    province: '',
    cityName: '',
  });
  //管理客户平台
  const manageVisible = ref<any>(false); //
  const manageConfirmLoading = ref<any>(false); //
  const currentItem = ref<any>({}); //
  const peopleData = ref<any>([]); // 系统管理
  const rootData = ref<any>([]); //
  // 查询表单数据
  const provinceOptions = ref<any[]>([]);
  //平台管理数据
  const platOptions = ref<any[]>([]);
  const addPlatList = ref<any>([]); // 新添加的平台
  const modalLoading = ref<any>(false); // 新添加的平台

  //省市
  const cityOptions = ref<any[]>([]); //省市

  const columns = [
    { title: '省', dataIndex: 'province', key: 'province' },
    { title: '市', dataIndex: 'cityName', key: 'cityName' },
    {
      title: '客户平台',
      dataIndex: 'platList',
      key: 'platList',
      slots: { customRender: 'platList' },
      width: 180,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      customRender: ({ text }) => {
        return moment(text).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    { title: '创建人', dataIndex: 'creator', key: 'creator' },
    {
      title: '操作',
      fixed: 'right',
      key: 'action',
      width: '150px',
      slots: { customRender: 'action' },
    },
  ];

  onMounted(() => {
    getTableDate();
    getDictRegionList(1);
    getPlatListAll();
  });
  //获取区域现货列表
  const getTableDate = () => {
    tableLoading.value = true;
    getScAreaListApi({
      currentPage: page.value,
      pageSize: pageSize.value,
    }).then((res) => {
      if (res.success) {
        tableData.value = res.data;
        total.value = res.data[0].total;
      } else {
        message.error(res.message);
      }
      tableLoading.value = false;
    });
  };
  //获取省
  const getDictRegionList = (level: any) => {
    dictRegionListApi({ provinceId: form.value.province, level }).then((res) => {
      if (res.success) {
        provinceOptions.value = res.data;
      } else {
        message.error(res.message);
      }
    });
  };
  //获取所有平台
  const getPlatListAll = () => {
    getPlatListAllApi({}).then((res) => {
      if (res.success) {
        platOptions.value = res.data;
      } else {
        platOptions.value = [];
        message.error(res.message);
      }
    });
  };
  //添加区域按钮
  const addBtn = () => {
    visible.value = true;
  };
  //省改变事件
  const onProvinceChange = () => {
    dictRegionListApi({ provinceId: form.value.province, level: 2 }).then((res) => {
      if (res.success) {
        cityOptions.value = res.data;
      } else {
        message.error(res.message);
      }
    });
    form.value.cityName = '';
    cityDisadble.value = false;
  };
  //添加区域确认事件
  const handleOk = () => {
    if (form.value.province == '' || form.value.cityName == '') {
      return message.warning('请选择省市');
    }
    let param = {
      provinceId: form.value.province,
      provinceName: provinceOptions.value.filter((item) => item.code == form.value.province)[0]
        .name,
      cityId: form.value.cityName,
      cityName: cityOptions.value.filter((item) => item.code == form.value.cityName)[0].name,
    };
    confirmLoading.value = true;
    addScAreaApi(param).then((res) => {
      if (res.success) {
        message.success(res.message);
      } else {
        message.error(res.message);
      }
      confirmLoading.value = false;
      cancelHandle();
      getTableDate();
    });
  };
  //添加区域取消事件
  const cancelHandle = () => {
    form.value.province = '';
    form.value.cityName = '';
    cityDisadble.value = true;
    confirmLoading.value = false;
    visible.value = false;
  };
  //管理客户平台按钮
  const manageBtn = (row) => {
    currentItem.value = row;
    manageVisible.value = true;
    modalLoading.value = true;
    getPlatListApi({ provinceId: row.provinceId, cityId: row.cityId }).then((res) => {
      if (res.success) {
        peopleData.value = res.data.filter((item) => item.type == 1);
        rootData.value = res.data.filter((item) => item.type == 0);
      } else {
        message.error(res.message);
      }
      modalLoading.value = false;
    });
  };

  //确认管理客户平台
  const manegeHandleOk = () => {
    if (addPlatList.value.length === 0) {
      manageVisible.value = false;
      return;
    }
    if (addPlatList.value.find((item) => item.platCode == '')) {
      return message.warning('请先选择要添加的平台！');
    }
    let param = {
      provinceId: currentItem.value.provinceId,
      province: currentItem.value.province,
      cityId: currentItem.value.cityId,
      city: currentItem.value.cityName,
      platCode: addPlatList.value.map((item) => item.platCode).join(','),
    };
    manageConfirmLoading.value = true;
    addScAreaPlatformApi(param).then((res) => {
      if (res.success) {
        message.success(res.message);
      } else {
        message.error(res.message);
      }
      manageConfirmLoading.value = false;
      manegecancelHandle();
      getTableDate();
    });
  };
  //管理客户平台取消按钮
  const manegecancelHandle = () => {
    manageVisible.value = false;
    addPlatList.value = [];
    peopleData.value = [];
    rootData.value = [];
  };
  //添加平台按钮
  const addPlatBtn = () => {
    if (addPlatList.value.find((item) => item.platCode == '')) {
      return message.warning('请先选择当前行的平台');
    }
    addPlatList.value.push({
      platCode: '',
    });
  };
  //删除平台按钮
  const removePlatBtn = (index) => {
    addPlatList.value.splice(index, 1);
  };
  //删除平台回调
  const removePeoplePlat = (item) => {
    Modal.confirm({
      title: '确认',
      content: `确认删除平台 ${item.platName} 吗？`,
      okText: '确认删除',
      cancelText: '取消',
      onOk: () => {
        removeScAreaPlatformApi({ sysid: item.id }).then((res) => {
          if (res.success) {
            message.success(res.message);
            getPlatListApi({
              provinceId: currentItem.value.provinceId,
              cityId: currentItem.value.cityId,
            }).then((res) => {
              if (res.success) {
                peopleData.value = res.data.filter((item) => item.type == 1);
                rootData.value = res.data.filter((item) => item.type == 0);
              } else {
                peopleData.value = [];
                rootData.value = [];
                message.error(res.message);
              }
            });
          } else {
            message.error(res.message);
          }
        });
      },
    });
  };

  //过滤搜索
  const filterOption = (input: string, option: any) => {
    return option.key.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };
  const filterOptionPlat = (input: string, option: any) => {
    return option.key.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };
</script>

<style lang="less" scoped>
  .complaints-page {
    //margin: 20px;

    .search-form {
      .search-header {
        background: #f7f8fc;
        padding: 5px 10px;
        display: flex;
        margin-bottom: 10px;

        .title {
          font-size: 18px;
          //font-weight: 600;
          font-family: 黑体;
          flex: 1;
        }
      }
    }
  }
  .box {
    padding: 10px 50px 10px 10px;
    .title {
      height: 50px;
      line-height: 50px;
      font-weight: 700;
      text-align: center;
      background: #fafafa;
      border: 1px solid #ddd;
    }
    .innerbox {
      div {
        position: relative;
        height: 40px;
        line-height: 40px;
        border-radius: 8px;
        .icon {
          position: absolute;
          right: -38px;
          top: 0;
        }
      }
    }
  }
  .addPlatSelect :deep(.ant-select-selector) {
    border: none;
  }
  .addPlatSelect :deep(.ant-select-arrow) {
    top: 35%;
  }
</style>
