<template>
  <div ref="posimanageeditAuth"></div>
  <n-modal v-model:show="state.showModal" :mask-closable="false">
    <n-card
      style="width: 80vw"
      :bordered="false"
      class="create-contianer"
      size="huge"
      width="1200px"
      role="dialog"
      aria-modal="true"
    >
      <template #header>
        <div class="title-visible">{{ props.title }}</div>
      </template>
      <template #header-extra>
        <img
          src="@/assets/image/icon/close-tabs.png"
          class="close-icon"
          @click="handleClose"
        />
      </template>

      <div class="center-content">
        <div class="left-box">
          <div class="title">基础设置</div>
          <div class="content" ref="modalSelect">
            <a-form
              ref="formRef"
              name="custom-validation"
              :model="formState"
              :rules="rules"
              v-bind="layout"
              :hideRequiredMark="true"
            >
              <a-form-item label="权限类型" name="type">
                <a-radio-group
                  v-model:value="formState.type"
                  @change="changeType"
                  name="radioGroup"
                >
                  <a-radio :value="'menu'">菜单权限</a-radio>
                  <a-radio :value="'button'">按钮权限</a-radio>
                  <a-radio :value="'interface'">列表字段权限</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item
                label="菜单管理"
                name="menuType"
                v-if="formState.type == 'menu'"
              >
                <a-radio-group
                  v-model:value="formState.menuType"
                  name="radioGroup"
                >
                  <a-radio :value="'1'">父级菜单</a-radio>
                  <a-radio :value="'2'">子级菜单</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item
                label="上级菜单"
                name="pid"
                v-if="formState.menuType == '2'"
              >
                <n-select
                  v-model:value="formState.pid"
                  :options="state.menuList"
                  label-field="Title"
                  value-field="ID"
                  filterable
                />
                <!-- <a-select ref="select"
                          v-model:value="formState.pid"
                          style="width: 200px">
                  <a-select-option v-for="(item,index) in state.menuList"
                                   :key="index"
                                   :value="item.ID">{{item.Title}}</a-select-option>
                </a-select> -->
              </a-form-item>
              <a-form-item label="权限名称" name="title">
                <n-input
                  v-model:value="formState.title"
                  autocomplete="off"
                  maxLength="12"
                  placeholder="最长输入12个字符"
                />
              </a-form-item>
              <a-form-item
                label="上级权限"
                name="pid"
                v-if="formState.type !== 'menu'"
              >
                <n-tree-select
                  filterable
                  v-model:value="formState.pid"
                  :options="state.menuTreeList"
                  @update:value="handleUpdatemenuTreeValue"
                />
              </a-form-item>
              <a-form-item label="路由/按钮名/接口名" name="url">
                <n-input
                  v-model:value="formState.url"
                  autocomplete="off"
                  :placeholder="
                    formState.type == 'menu' ? '不做路由跳转可为空' : ''
                  "
                />
              </a-form-item>
              <a-form-item
                label="图标"
                name="icon"
                v-if="formState.type == 'menu' && formState.menuType == '1'"
              >
                <Upload
                  :maxCount="1"
                  v-model:uploadVal="formState.icon"
                  :zIndex="9000"
                  class="upload"
                />
              </a-form-item>
              <a-form-item
                label="选中图标"
                name="grayIcon"
                v-if="formState.type == 'menu' && formState.menuType == '1'"
              >
                <Upload
                  :maxCount="1"
                  v-model:uploadVal="formState.grayIcon"
                  :zIndex="9000"
                  class="upload"
                />
              </a-form-item>
              <a-form-item
                label="排序"
                name="weigh"
                v-if="formState.type == 'menu'"
              >
                <n-input-number
                  :show-button="false"
                  v-model:value="formState.weigh"
                  autocomplete="off"
                  placeholder="1-100,越大排序越靠前"
                />
              </a-form-item>
            </a-form>
            <div v-show="formState.type == 'interface'" class="row">
              <div class="col-4 text-right">
                列表字段<span style="margin: 0 8px 0 2px">:</span>
              </div>
              <div class="col-8">
                <div
                  v-for="(item, index) in formState.ruleFields"
                  :key="index"
                  style="margin-bottom: 10px"
                >
                  <div class="flex">
                    <n-input
                      v-model:value="item.fieldCnName"
                      autocomplete="off"
                      placeholder="列表字段中文名称"
                      style="margin-bottom: 10px; width: 200px"
                    />
                    <span
                      class="cancel-btn"
                      @click="cancelRule(index)"
                      v-if="formState.ruleFields.length > 1"
                      >移除</span
                    >
                  </div>
                  <n-input
                    type="textarea"
                    v-model:value="item.fieldKey"
                    placeholder="列表字段对应value值"
                    :autosize="{ minRows: 2, maxRows: 5 }"
                  />
                </div>
              </div>
              <div class="col-4 row"></div>
              <div class="col-8 row">
                <a-button @click="addInput" style="width: 120px">
                  <PlusOutlined />
                </a-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="row justify-end">
          <div class="footer-content" v-if="state.isEdit">
            <!-- <a-popconfirm title="是否确认删除该权限，删除后不可恢复？"
                      cancel-text="取消"
                      ok-text="确定"
                      @confirm="handleDel"
                      @cancel="departmentCel">
          <a-button class="basic-btn">删除该权限</a-button>
        </a-popconfirm> -->
            <a-button
              class="primary-btn"
              :loading="state.btnLoading"
              @click="handleUpdate"
              >完成修改</a-button
            >
          </div>
          <div class="footer-content" v-else>
            <a-button class="basic-btn" @click="resetForm">清空</a-button>
            <a-button
              class="primary-btn"
              :loading="state.btnLoading"
              @click="handleCreate"
              >完成设置</a-button
            >
          </div>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup>
// 权限新建弹窗 旧代码
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons-vue";
import {
  defineProps,
  defineEmits,
  watch,
  reactive,
  ref,
  unref,
  onMounted,
  getCurrentInstance,
} from "vue";
import Upload from "@/components/upload.vue";
import { Form, message } from "ant-design-vue";
import { processSuccess, processError } from "@/utils/helper/message";

const currentInstance = getCurrentInstance();
const { $request } = currentInstance.appContext.config.globalProperties;

const emits = defineEmits(["submit", "triggerClose"]);
let props = defineProps({
  title: {
    type: String,
    require: true,
  },
  data: {
    type: Object,
    default: () => {},
  },
});
const state = reactive({
  btnLoading: false,
  menuList: [],
  menuTreeList: [],
  isEdit: false,
  showModal: true,
});
onMounted(() => {
  state.showModal = true;
  getMenu();
  getMenuTree();
  if (props.data?.id) {
    state.isEdit = true;
    getDetail();
  } else {
    state.isEdit = false;
    formState.dataOpen = true;
    formState.method = "*";
    formState.type = "";
    formState.icon = "";
    formState.pid = null;
    formState.title = "";
    formState.menuType = "";
    formState.url = "";
    formState.weigh = "";
    formState.ruleFields = [{ fieldKey: "", fieldCnName: "" }];
  }
});

const handleClose = () => {
  emits("triggerClose");
  resetForm();
  state.isEdit = false;
};
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const formRef = ref();
const formState = reactive({
  grayIcon: "",
  dataOpen: true,
  method: "*",
  type: "", // 'menu'菜单,'button'按钮组件,'interface'列表字段权限
  icon: "",
  pid: null,
  title: "",
  menuType: "",
  url: "",
  weigh: "",
  ruleFields: [{ fieldKey: "", fieldCnName: "" }],
});
const filedJsonV = async (_rule, value) => {
  // 验空
  if (
    formState.type === "interface" &&
    formState.ruleFields.some((val) => val.fieldKey == "" || val.fieldKey == "")
  ) {
    return Promise.reject("请补充完整");
  } else {
    return Promise.resolve();
  }
};
const urlV = async (_rule, value) => {
  // 验空
  if (formState.type === "menu" && formState.menuType === "1") {
    return Promise.resolve();
  } else {
    if (value == "") {
      return Promise.reject("请输入路由/唯一标识");
    } else {
      return Promise.resolve();
    }
  }
};
const rules = {
  type: [{ required: true, message: "请选择权限类型", trigger: "change" }],
  icon: [{ required: true, message: "请上传Icon", trigger: "change" }],
  grayIcon: [{ required: true, message: "请上传选中Icon", trigger: "change" }],
  menuType: [{ required: true, message: "请选择菜单等级", trigger: "change" }],
  pid: [
    { required: true, message: "请选择上级权限/上级菜单", trigger: "change" },
  ],
  title: [{ required: true, message: "请输入权限名称", trigger: "change" }],
  url: [{ required: true, validator: urlV, trigger: "change" }], // message: '请输入路由/唯一标识',
  weigh: [{ required: true, message: "请输入排序", trigger: "change" }],
  ruleFields: [
    {
      required: true,
      validator: filedJsonV,
      trigger: ["blur, change"],
      type: "array",
    },
  ],
};
const resetForm = () => {
  formRef.value.resetFields();
};
const addInput = () => {
  formState.ruleFields.push({ fieldKey: "", fieldCnName: "" });
};
const cancelRule = (index) => {
  formState.ruleFields.splice(index, 1);
};
const changeType = () => {
  formState.dataOpen = true;
  formState.method = "*";
  // formState.type = ''
  formState.icon = "";
  formState.pid = null;
  formState.title = "";
  formState.url = "";
  formState.weigh = "";
  formState.menuType = "";
  formState.ruleFields = [{ fieldKey: "", fieldCnName: "" }];
};

const handleCreate = () => {
  formRef.value
    .validate()
    .then(() => {
      formState.pid = formState.pid ? Number(formState.pid) : 0;
      formState.weigh = formState.weigh ? Number(formState.weigh) : 1;

      state.btnLoading = true;
      let url = "/rule/create";
      let params = formState;
      $request.HTTP.components.postDataByParams(url, params).then(
        (res) => {
          state.btnLoading = false;
          if (res.status === 0) {
            processSuccess("添加成功");
            handleClose();
            emits("triggerClose");
          } else {
            processError(res.msg || "操作失败！");
          }
        },
        () => {
          state.btnLoading = false;
          processError("操作失败！");
        }
      );
    })
    .catch((error) => {});
};
const handleDel = () => {
  $request.HTTP.permission
    .ruleRemove({ ID: formState.ID })
    .then((res) => {
      if (res.status == 0) {
        message.success({
          content: "删除成功",
          duration: 2,
          onClose() {
            handleClose();
            emits("triggerClose");
          },
        });
      } else {
        message.error(res.msg);
      }
    })
    .catch((e) => {
      message.error(e.response?.data?.msg || "操作失败，请稍后再试");
    });
};
const departmentCel = () => {};
const handleUpdate = () => {
  formRef.value
    .validate()
    .then(() => {
      formState.pid = formState.pid ? Number(formState.pid) : 0;
      formState.weigh = formState.weigh ? Number(formState.weigh) : 1;

      state.btnLoading = true;
      let url = "/rule/v2/update";
      let params = formState;
      $request.HTTP.components.postDataByParams(url, params).then(
        (res) => {
          state.btnLoading = false;
          if (res.status === 0) {
            message.success({
              content: "修改成功",
              duration: 2,
              onClose() {
                handleClose();
                emits("triggerClose");
              },
            });
          } else {
            processError(res.msg || "操作失败！");
          }
        },
        () => {
          state.btnLoading = false;
          processError("操作失败！");
        }
      );
    })
    .catch(() => {});
};

const getMenu = () => {
  $request.HTTP.permission
    .menuFList()
    .then((res) => {
      if (res.status == 0) {
        state.menuList = res.data.data;
      } else {
        message.error(res.msg);
      }
    })
    .catch((e) => {
      message.error(e.response?.data?.msg || "操作失败，请稍后再试");
    });
};

const getMenuTree = () => {
  $request.HTTP.permission
    .menuSList()
    .then((res) => {
      if (res.status == 0) {
        state.menuTreeList = res.data.data.map((item) => {
          let obj = {
            label: item.Title,
            key: item.ID,
            children: [],
          };
          if (item.Son) {
            obj.children = item.Son.map((i) => {
              return {
                key: i.ID,
                label: i.Title,
              };
            });
          }
          return obj;
        });
      } else {
        message.error(res.msg);
      }
    })
    .catch((e) => {
      message.error(e.response?.data?.msg || "操作失败，请稍后再试");
    });
};
const handleUpdatemenuTreeValue = (val) => {
  formState.pid = val;
};
const getDetail = () => {
  let url = "/rule/v2/detail";
  let params = {
    ID: props.data.id,
  };
  $request.HTTP.components.postDataByParams(url, params).then(
    (res) => {
      if (res.status === 0) {
        formState.ID = res.data.ID;
        formState.type = res.data.type;
        formState.title = res.data.title;
        formState.url = res.data.url;
        if (res.data.type == "button") {
          formState.pid = res.data.pid;
        }
        if (res.data.type == "menu") {
          formState.icon = res.data.icon;
          formState.grayIcon = res.data.grayIcon;
          formState.weigh = res.data.weigh;
          formState.pid = res.data.pid;
          formState.menuType = res.data.menuType;
        }
        if (res.data.type == "interface") {
          formState.pid = res.data.pid;
          formState.ruleFields = res.data.ruleFields;
        }
      } else {
        processError(res.msg || "获取失败！");
      }
    },
    () => {
      processError("获取失败！");
    },
    () => {
      processError("获取失败！");
    }
  );
};
</script>

<style lang="scss" scoped>
.title-visible {
  text-align: center;
  color: $theme-primary;
  font-size: 22px;
}
:deep(.ant-modal-body) {
  padding: 0 24px;
}
.create-contianer {
  .ant-input {
    color: #6d5c9c;
  }
  .center-content {
    height: 65vh;
    display: flex;
    .title {
      width: fit-content;
      padding-left: 10px;
      border-left: 4px solid $theme-primary;
      color: $text-theme;
      margin: 19px 0;
    }

    .left-box {
      width: 55%;
      padding-right: 30px;
      .content {
        height: 54vh;
        overflow-y: auto;
      }
      div {
        color: $text-theme;
      }
      :deep(.ant-form-item-label > label) {
        color: $text-theme;
      }
      .ant-form-item input[type="text"],
      input,
      textarea {
        background: #e3dfea;
      }

      .ant-select :deep(.ant-select-selector) {
        background: #e3dfea;
      }
      .control-item {
        :deep(.ant-form-item-control) {
          margin-left: 0px !important;
        }
      }
      .flex {
        display: flex;
        justify-content: space-between;
      }
      .cancel-btn {
        color: #999999;
        cursor: pointer;
        &:hover {
          color: $text-theme;
        }
      }
    }
  }
  .upload {
    :deep(.ant-image) {
      width: 100px;
      height: 100px;
    }
    :deep(.ant-image-img) {
      width: 100px;
      height: 100px;
    }
  }
  .footer-content {
    margin: 10px 0;
    button {
      width: 130px;
      height: 30px;
      text-align: center;
      line-height: 30px;
      padding: 0;
      margin: 0 10px;
      border-radius: 20px;
    }
  }
}
</style>
