<template>
  <my-dialog
    :visible="visible"
    :header="title"
    :width="600"
    attach="body"
    :closeOnOverlayClick="false"
    @close="emit('update:visible', false)"
    @opened="dialogOpened"
  >
    <t-form ref="formRef" :data="formData" :rules="rules" labelAlign="top">
      <t-row :gutter="[20, 20]">
        <t-col :span="6">
          <t-form-item label="服务档位名称" name="level">
            <t-input v-model="formData.level" clearable />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="业务类型" name="type">
            <t-select v-model="formData.type">
              <t-option
                v-for="(val, key) in CUSTOMER_TYPE"
                :key="key"
                :label="val"
                :value="key"
              />
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="项目角色配置" name="roleList" required-mark>
            <div>
              <t-table
                size="small"
                row-key="roleId"
                :columns="roleColumns"
                :data="formData.roleList"
                bordered
              >
                <template #quota="{ row }">
                  <t-input-number
                    v-model="row.quota"
                    theme="column"
                    :decimalPlaces="0"
                    :max="1000"
                    :min="1"
                    style="width: 100px"
                  ></t-input-number>
                </template>
                <template #operate="{ row }">
                  <div class="table-operations">
                    <t-link
                      theme="primary"
                      hover="color"
                      @click="handleDelete(row)"
                    >
                      删除
                    </t-link>
                  </div>
                </template>
              </t-table>
            </div>
          </t-form-item>
          <t-form-item>
            <div class="flex justify-between items-center" style="width: 100%">
              <!-- <select-role
                v-model="selectedRoleId"
                @change="roleChange"
              ></select-role> -->
              <t-select v-model="selectedRoleId" @change="roleChange">
                <t-option
                  v-for="item in roleList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                  :disabled="configRoleIds.includes(item.id)"
                ></t-option>
              </t-select>
              <t-button
                class="m-l-10px"
                theme="primary"
                :disabled="!selectedRole"
                @click="toAddRole"
                >添加</t-button
              >
            </div>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="设备配额" name="devices">
            <t-input-number
              v-model="formData.devices"
              theme="column"
              :decimalPlaces="0"
              :max="1000"
              :min="1"
              style="width: 100%"
            />
          </t-form-item>
        </t-col>
      </t-row>
    </t-form>
    <template #foot>
      <t-button theme="default" @click="emit('update:visible', false)"
        >取消</t-button
      >
      <t-button theme="primary" @click="save">保存</t-button>
    </template>
  </my-dialog>
</template>
<script setup name="EditServiceLevelDialog">
import { ref, computed } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import useClearDialog from '@/hooks/useClearDialog';
import useAuthenRole from '@/hooks/useAuthenRole';
import { CUSTOMER_TYPE } from '@/config/constants';
import { serviceLevelEditApi } from '@/api/system';

const emit = defineEmits(['update:visible', 'success']);
const props = defineProps({
  visible: Boolean,
  curRow: Object,
});

const formRef = ref(null);
let selectedRole = ref(null);
let selectedRoleId = ref(null);

const title = computed(() => {
  return (isEdit.value ? '编辑' : '新增') + '服务档位';
});
const configRoleIds = computed(() => {
  return formData.roleList.map((item) => item.roleId);
});

const { roleList, getRoleList } = useAuthenRole();

const { formData, isEdit } = useClearDialog(
  {
    id: null,
    level: '',
    type: '',
    devices: null,
    enable: true,
    roleList: [],
  },
  props,
  formRef,
  () => {
    for (let key in formData) {
      formData[key] = props.curRow[key];
    }
  }
);
const rules = {
  level: [
    { required: true, message: '名称必填', type: 'error', trigger: 'change' },
    {
      min: 2,
      message: '至少需要2个字',
      type: 'error',
      trigger: 'change',
    },
    {
      max: 50,
      message: '至多需要50个字',
      type: 'error',
      trigger: 'change',
    },
  ],
  type: [
    {
      required: true,
      message: '业务类型必选',
      type: 'error',
      trigger: 'change',
    },
  ],
  roleList: [
    {
      validator: (val) => {
        if (!val || !val.length)
          return { result: false, message: '请填写至少一个角色' };

        if (val.some((item) => !item.quota))
          return { result: false, message: '有角色未设置配额' };

        return { result: true, type: 'success' };
      },
      type: 'error',
      trigger: 'change',
    },
  ],
  devices: [
    {
      validator: (val) => {
        if (Number(val) <= 0) {
          return { result: false, message: '设备配额必须大于0' };
        }
        return { result: true, type: 'success' };
      },
      type: 'error',
      trigger: 'change',
    },
  ],
};

const roleColumns = [
  { colKey: 'roleName', title: '项目角色' },
  { colKey: 'quota', title: '配额', cell: 'quota', width: 130 },
  { colKey: 'operate', title: '管理', cell: 'operate', width: 60 },
];

const dialogOpened = () => {
  selectedRole.value = null;
  selectedRoleId.value = null;
  getRoleList();
};

const roleChange = () => {
  selectedRole.value = roleList.value.find(
    (item) => item.id === selectedRoleId.value
  );
};
const toAddRole = () => {
  if (formData.roleList.some((item) => item.roleId === selectedRole.value.id)) {
    MessagePlugin.error('当前角色已经被选过！');
    return;
  }

  formData.roleList.push({
    quota: 1,
    roleId: selectedRole.value.id,
    roleName: selectedRole.value.name,
  });

  selectedRole.value = null;
  selectedRoleId.value = null;
};
const handleDelete = (row) => {
  formData.roleList = formData.roleList.filter(
    (item) => item.roleId !== row.roleId
  );
};

const save = async () => {
  const valid = await formRef.value.validate();
  if (valid !== true) return;

  const res = await serviceLevelEditApi(formData).catch(() => {});
  if (!res) return;

  MessagePlugin.success('保存成功');
  emit('update:visible', false);
  emit('success');
};
</script>
