<script lang="ts" setup>
import { ref, watch, shallowRef } from "vue"
import { useVModel } from "@vueuse/core"
import { useCompany } from "/@/hooks/core/useCompany";
import { BusinessQuery } from "/@/components/BasicForm";
import { httpList, httpUpdate } from "/@/api/interest/role";

import { httpDetail, httpAdd } from "/@/api/interest/role";

import { ElMessage } from "element-plus"

const props = defineProps<{
  companyNo: string
  roleName: string
  visible: boolean
  roleId: string
}>()

const emit = defineEmits(['refresh'])


const visible = useVModel(props, 'visible')
const formRef = ref<any>(null)
const { currentCompany } = useCompany();


const roles = ref<any[]>([])
const loading = shallowRef(false)

const initialData = {
  name: '',
  companyNo: '',
  sourceRoleId: '',
  sourceCompanyNo: ''
}

const formData = ref({ ...initialData })


watch(
  () => currentCompany.value,
  () => formData.value.companyNo = currentCompany.value.companyNo
);

async function requestRoles(companyNo: string) {
  loading.value = true;
  const { code, data, message } = await httpList({
    size: 1000,
    level: "2",
    companyNo
  });

  if (code === 0) {
    const { list, count } = data;
    roles.value = list
  }

  loading.value = false;
}

watch(() => formData.value.sourceCompanyNo, (value) => {
  roles.value = []
  formData.value.sourceRoleId = ""
  if (!formData.value.sourceCompanyNo) { return }
  requestRoles(formData.value.sourceCompanyNo)
}, {
  immediate: true
})

const rules = {
  // "name": [{ required: true, message: '请输入角色名称', trigger: 'change' }],
  "sourceCompanyNo": [{ required: true, message: '请选择来源业务公司', trigger: 'change' }],
  "sourceRoleId": [{ required: true, message: '请选择来源角色', trigger: 'change' }],
}

function handleClose() {
  formData.value = { ...initialData }
  visible.value = false
}

async function requestRole() {
  try {
    const { sourceCompanyNo, sourceRoleId } = formData.value
    const { data, code } = await httpDetail({ companyNo: sourceCompanyNo, roleid: sourceRoleId });
    if (code === 0) {
      return data
    } else {
      throw new Error('读取角色失败..')
    }
  } catch (err) {
    throw new Error('读取角色失败..')
  }
}

async function createRole(params = {}) {
  try {
    const { data, code } = await httpUpdate(params);
    if (code !== 0) { throw new Error('复制角色失败..') }
  } catch (err) {
    throw new Error('复制角色失败..')
  }
}


async function onSubmit() {
  try {
    loading.value = true
    await formRef.value.validate();
    const { sourceCompanyNo, sourceRoleId, companyNo, name } = formData.value
    ElMessage.info('正在读取来源角色信息(1/3)...')
    const detail = await requestRole()
    ElMessage.info('读取角色信息成功,正在复制角色(2/3)...')
    const { action, private_data, role_name } = detail;
    const params = {
      level: 2,
      roleid: props.roleId,
      role_name: props.roleName,
      companyNo: props.companyNo,
      action: Array.isArray(action) ? action : action.split(','),
      private_data:( Array.isArray(private_data) ? private_data : private_data.split(',')).filter(item => !!item)
    };
    await createRole(params)
    loading.value = false
    ElMessage.success('角色复制成功(3/3)...')
    emit('refresh')
    visible.value = false
  } catch (err) {
    ElMessage.warning(err)
    loading.value = false
  }
}
</script>

<template>
  <ElDialog title="复制角色" center v-model="visible" @close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <ElForm :model="formData" :rules="rules" ref="formRef" v-loading="loading" label-width="80px">
      <ElFormItem prop="name" label="角色名称">
        <ElInput :modelValue="roleName" placeholder="角色名称" disabled />
      </ElFormItem>

      <ElFormItem prop="sourceCompanyNo" label="来源公司">
        <BusinessQuery v-model="formData.sourceCompanyNo" placeholder="来源公司" />
      </ElFormItem>

      <ElFormItem prop="sourceRoleId" label="来源角色">
        <ElSelect v-model="formData.sourceRoleId" style="width:100%" placeholder="来源角色"
          :disabled="!formData.sourceCompanyNo">
          <ElOption v-for="role in roles" :key="role.id" :value="role.id" :label="role.role_name" :disabled="role.id === roleId" />
        </ElSelect>
      </ElFormItem>

      <div class="w-full flex justify-end">
        <ElButton type="primary" @click="onSubmit">保存</ElButton>
      </div>
    </ElForm>
  </ElDialog>
</template>
