<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import {
    Form,
    Card,
    FormItem,
    SelectOption,
    Select,
    Radio,
    RadioGroup,
    Input,
    Divider,
    Pagination,
    Button,
    message,
  } from 'ant-design-vue';
  import VNodes from '/@/components/VNodes';
  import { authorizeCloseApi, authorizeGetDropdownApi, authorizeUpdateApi } from '/@/api/authorize';
  import { authorizeClassListApi } from '/@/api/authorize/class';
  import { useData } from '/@/hooks/data/useData';
  import { useRouter, useRoute } from 'vue-router';

  const router = useRouter();
  const route = useRoute();
  const requestList = {
    list: authorizeGetDropdownApi, // 列表接口
  };

  const searchForm = ref<any>({}); // 查询表单数据

  const isDetail = ref<boolean>(false); // 是否是查看页

  onMounted(async () => {
    const { id, detail } = route.query;
    await initTableData();
    if (id) {
      form.value.id = Number(id);
      detail ? (isDetail.value = true) : (isDetail.value = false);
      initDetail();
    }
  });

  const tableList = ref<any[]>([]);

  const initTableData = async () => {
    try {
      const res = await authorizeClassListApi({});
      tableList.value = res.map((el) => {
        return {
          ...el,
          items: el.items
            .map((e) => ({
              ...e,
              value: 0,
            }))
            .sort((a, b) => a.sort > b.sort),
        };
      });
    } catch (e) {
      console.log(e);
    }
  };

  const {
    onSearch,
    onPageChange, //  页码改变的回调
    pager, // 分页的数据
    tableData, //  表格数据
  } = useData<any, any>(requestList, searchForm);

  const handleSearch = (e) => {
    searchForm.value.key_ = e;
    onSearch();
    console.log(e);
  };

  const handleFocus = () => {
    searchForm.value.key_ = '';
    onSearch();
  };

  const initDetail = async () => {
    try {
      const res: any = await authorizeCloseApi(form.value.id);
      const { supplierId, authorizeFlag, authorizeCode, authorizeVipcode, authorizeItems, id } =
        res;
      form.value = {
        supplierId: Number(supplierId),
        authorizeFlag,
        authorizeCode,
        authorizeVipcode,
        id,
      };
      tableList.value.forEach((el) => {
        el.items.forEach((e) => {
          const valueObj = authorizeItems.find((item) => item.code === e.code);
          e.value = valueObj?.value || 0;
        });
      });
    } catch (e) {
      console.log(e);
    }
  };

  const form = ref<any>({
    supplierId: undefined,
    authorizeFlag: undefined,
    authorizeCode: '',
    authorizeVipcode: '',
  });

  const rules = reactive({
    supplierId: [{ required: true, message: '供应商不能为空', trigger: ['change', 'blur'] }],
    authorizeFlag: [{ required: true, message: '请选择是否开启授权', trigger: ['change', 'blur'] }],
    authorizeCode: [{ required: true, message: '请输入授权码', trigger: ['change', 'blur'] }],
    authorizeVipcode: [{ required: true, message: '请输入会员吗', trigger: ['change', 'blur'] }],
  });

  // const tableList = ref<any>([
  //   {
  //     type: '商品数据接口',
  //     code: 1,
  //     children: [
  //       { name: '图片素材上传', value: 1, code: 2 },
  //       { name: '商品信息同步', value: 1, code: 3 },
  //       { name: '目录更新均价', value: 1, code: 4 },
  //       { name: '促销信息更新', value: 1, code: 5 },
  //       { name: '按品牌分类删除/下架', value: 1, code: 6 },
  //       { name: '自定义删除/下架', value: 1, code: 7 },
  //     ],
  //   },
  //   {
  //     type: '订单数据接口',
  //     code: 8,
  //     children: [
  //       { name: '订单信息同步', value: 1, code: 9 },
  //       { name: '订单信息更新', value: 1, code: 10 },
  //       { name: '订单信息删除', value: 1, code: 11 },
  //       { name: '订单信息查询', value: 1, code: 12 },
  //     ],
  //   },
  // ]);
  const cancelBtn = () => {
    router.go(-1);
  };
  const formRef = ref();

  const submitBtn = async () => {
    try {
      // console.log(
      //   tableList.value.map((el: any) => {
      //     return el.items.map((e: any) => ({
      //       code: e.code,
      //       value: e.value,
      //     }));
      //   }).flat(),
      // );
      await formRef.value.validate();
      const res = await authorizeUpdateApi({
        ...form.value,
        powerJson: tableList.value
          .map((el: any) => {
            return el.items.map((e: any) => ({
              name: e.code,
              value: e.value,
            }));
          })
          .flat(),
      });
      message.success('提交成功');
      cancelBtn();
    } catch (e) {
      console.log(e);
    }
  };
</script>

<template>
  <Card>
    <Form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 14 }"
    >
      <FormItem label="供应商名称" name="supplierId">
        <Select
          v-model:value="form.supplierId"
          placeholder="请选择供应商"
          style="width: 100%"
          option-filter-prop="children"
          :default-active-first-option="false"
          :show-arrow="false"
          :filter-option="false"
          showSearch
          allowClear
          :not-found-content="null"
          @search="handleSearch"
          @focus="handleFocus"
          :get-popup-container="(el) => (el ? el.parentNode : document.body)"
          :disabled="form.id"
        >
          <template #dropdownRender="{ menuNode: menu }">
            <v-nodes :vnodes="menu" />
            <Divider style="margin: 8px 0" />
            <div
              style="padding: 0px 8px 8px; cursor: pointer"
              @mousedown="(e) => e.preventDefault()"
            >
              <Pagination
                size="small"
                :default-current="pager.page"
                :page-size="pager.pageSize"
                :total="pager.total"
                @change="onPageChange"
              />
            </div>
          </template>
          <SelectOption v-for="item in tableData" :key="item.key" :value="item.key">
            {{ item.value }}
          </SelectOption>
        </Select>
      </FormItem>
      <FormItem label="是否授权" name="authorizeFlag">
        <RadioGroup v-model:value="form.authorizeFlag" :disabled="isDetail">
          <Radio :value="1">开启授权</Radio>
          <Radio :value="0">终止授权</Radio>
        </RadioGroup>
      </FormItem>
      <template v-if="form.authorizeFlag === 1">
        <FormItem label="会员授权码" name="authorizeVipcode">
          <Input v-model:value="form.authorizeVipcode" :disabled="form.id" />
        </FormItem>
        <FormItem label="安全验证码" name="authorizeCode">
          <Input v-model:value="form.authorizeCode" :disabled="form.id" />
        </FormItem>
        <FormItem label="接口调用授权" name="key_">
          <table>
            <thead>
              <tr>
                <th>接口分类</th>
                <th>接口名称</th>
                <th>授权状态</th>
              </tr>
            </thead>
            <tbody>
              <template v-for="item in tableList" :key="item.type">
                <tr v-for="(inter, index) in item.items" :key="inter.name">
                  <td v-if="!index" :rowspan="item.items.length">{{ item.name }}</td>
                  <td>{{ inter.content }}</td>
                  <td>
                    <RadioGroup v-model:value="inter.value" :disabled="isDetail">
                      <Radio :value="1">开启授权</Radio>
                      <Radio :value="0">终止授权</Radio>
                    </RadioGroup>
                  </td>
                </tr>
              </template>
            </tbody>
          </table>
        </FormItem>
      </template>
      <FormItem v-if="!isDetail">
        <Button style="margin: 5px 0" type="primary" @click="submitBtn">确定</Button>
        <Button style="margin: 5px 0" @click="cancelBtn">取消</Button>
      </FormItem>
    </Form>
  </Card>
</template>

<style lang="less" scoped>
  table {
    tr,
    th,
    td {
      border: 1px solid @border-color-base;
      text-align: center;
    }

    th {
      padding: 10px 20px;
      background: @table-header-bg;
      color: @table-header-color;
    }

    td {
      padding: 10px 20px;
    }
  }
</style>
