<script setup lang="ts">
import { ref, computed, reactive } from "vue";
import { useAsync } from "/@/hooks";
import { ElForm } from "element-plus";
import { rules } from "../../company/config/configs";

import {
  httpUserList,
  httpMenuList,
  httpUserGroup,
  httpAdd,
  httpDetail,
  httpUpdate
} from "/@/api/interest/dataShare";

const emit = defineEmits(["reload"]);

const id = ref("");
const readonly = ref(false);

const visible = ref(false);
const formRef = ref<InstanceType<typeof ElForm>>(null);
const isCreate = computed(() => !id.value);

const initalData = {
  menu_ids: [],
  source_uid: "",
  source_data_group_id: "",
  uid: "",
  data_group_id: "",
  type: "2"
};

const shareTypes = reactive({
  source: "1",
  target: "1"
});

const title = computed(() => {
  if (readonly.value) return "数据共享详情";
  return isCreate.value ? "创建数据共享" : "编辑数据共享";
});

const onBeforeAction = () => {
  visible.value = false;
  emit("reload");
};

const initalLoading = computed(
  () =>
    groupLoading.value ||
    menuLoading.value ||
    userLoading.value ||
    detailLoading.value
);
const actionLoading = computed(
  () => createLoading.value || updateLoading.value
);

const formData = ref({ ...initalData });

const {
  run: userlistRun,
  data: userlist,
  loading: userLoading
} = useAsync<Array<Record<string, string>>>({
  initalData: []
});

const {
  run: menulistRun,
  data: menulist,
  loading: menuLoading
} = useAsync<Array<Record<string, string>>>({
  initalData: []
});

const {
  run: grouplistRun,
  data: grouplist,
  loading: groupLoading
} = useAsync<Array<Record<string, string>>>({
  initalData: [],
  isList: true
});

const { run: createDataShareRun, loading: createLoading } = useAsync({
  success: () => onBeforeAction()
});
const { run: updateDateShareRun, loading: updateLoading } = useAsync({
  success: () => onBeforeAction()
});

const {
  run: dataShareDetailRun,
  data: dataShareDetail,
  loading: detailLoading
} = useAsync<Record<string, any>>({
  initalData: {},
  success: () => {
    let {
      menu_list,
      source_data_group_id,
      data_group_id,
      uid,
      source_uid,
      type
    } = dataShareDetail.value;

    shareTypes.source = source_uid === "0" ? "2" : "1";
    shareTypes.target = uid === "0" ? "2" : "1";

    data_group_id = data_group_id === "0" ? "" : data_group_id;
    source_data_group_id =
      source_data_group_id === "0" ? "" : source_data_group_id;
    uid = uid === "0" ? "" : uid;
    source_uid = source_uid === "0" ? "" : source_uid;

    formData.value = {
      menu_ids: menu_list.map(({ id }) => id),
      source_data_group_id,
      data_group_id,
      source_uid,
      uid,
      type
    };
  }
});

function createDataShare() {
  createDataShareRun(httpAdd(formData.value));
}

function updateDataShare() {
  updateDateShareRun(
    httpUpdate({
      id: id.value,
      ...formData.value
    })
  );
}

function handleConfirm() {
  formRef.value.validate(isValid => {
    console.log(isValid);
    if (!isValid) return;

    if (isCreate.value) return createDataShare();

    updateDataShare();
  });
}

defineExpose({
  onDisplay(_id = "", _readonly = false) {
    visible.value = true;
    userlistRun(httpUserList({size: 100}));
    menulistRun(httpMenuList({size: 100}));
    grouplistRun(httpUserGroup({size:100}));
    readonly.value = _readonly;
    id.value = _id;

    if (!_id) return (formData.value = { ...initalData });

    dataShareDetailRun(httpDetail({ id: id.value }));
  }
});
</script>

<template>
  <el-dialog :close-on-click-modal="false" v-model="visible" :title="title" center
    @close="() => (formData = { ...initalData })">
    <el-form label-width="120px" ref="formRef" :model="formData" :disabled="readonly" v-loading="initalLoading"
      :rules="rules">
      <el-form-item prop="menu_ids" label="共享的菜单数据">
        <el-select w-full v-model="formData.menu_ids" multiple>
          <el-option-group v-for="menu in menulist" :key="menu.id" :label="menu.menu_name">
            <el-option v-for="(item, i) in menu.child" :key="'item' + item.menu_name + i" :label="item.menu_name"
              :value="item.id" />
          </el-option-group>
        </el-select>
      </el-form-item>

      <el-form-item label="数据源共享对象" :prop="shareTypes.source === '1' ? 'source_uid' : 'source_data_group_id'
    ">
        <el-select w-100px v-model="shareTypes.source" @change="val =>
      val === '1'
        ? (formData.source_data_group_id = '')
        : (formData.source_uid = '')
    ">
          <el-option value="1" label="用户" />
          <el-option value="2" label="用户组" />
        </el-select>
        <el-select flex-1 placeholder="请选择用户" v-if="shareTypes.source === '1'" v-model="formData.source_uid">
          <el-option v-for="user in userlist" :key="user.id" :value="user.id" :label="user.nickname" />
        </el-select>
        <el-select flex-1 placeholder="请选择用户组" v-else v-model="formData.source_data_group_id">
          <el-option v-for="group in grouplist" :key="group.id" :value="group.id" :label="group.title" />
        </el-select>
      </el-form-item>

      <el-divider />

      <el-form-item label="数据共享对象" :prop="shareTypes.target === '1' ? 'uid' : 'data_group_id'">
        <el-select w-100px v-model="shareTypes.target" @change="val =>
      val === '1' ? (formData.source_uid = '') : (formData.uid = '')
    ">
          <el-option value="1" label="用户" />
          <el-option value="2" label="用户组" />
        </el-select>
        <el-select flex-1 placeholder="请选择用户" v-if="shareTypes.target === '1'" v-model="formData.uid">
          <el-option v-for="user in userlist" :key="user.id" :value="user.id" :label="user.nickname" />
        </el-select>
        <el-select flex-1 placeholder="请选择用户组" v-else v-model="formData.data_group_id">
          <el-option v-for="group in grouplist" :key="group.id" :value="group.id" :label="group.title" />
        </el-select>
      </el-form-item>

      <el-form-item label="共享的数据权限" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio label="2">只读</el-radio>
          <el-radio label="1">读写</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <div w-full flex justify-end>
          <el-button type="primary" @click="() => handleConfirm()" :loading="actionLoading">提交
          </el-button>
          <el-button @click="() => (visible = false)">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
