<script setup lang="tsx">
import type { ElIcon } from 'element-plus';

// @ts-ignore
import type { VxeGridProps } from '#/adapter/vxe-table';

import { onMounted, ref } from 'vue';

// @ts-ignore
import { useVbenDrawer, useVbenForm, useVbenModal } from '@vben/common-ui';

// @ts-ignore
import { Delete } from '@element-plus/icons-vue';
// @ts-ignore
import { ElInputNumber, ElMessage } from 'element-plus';

// @ts-ignore
import { useVbenVxeGrid } from '#/adapter/vxe-table';
// @ts-ignore: 忽略
import { employeeSettingsList } from '#/api/system/infoEntry/employeeSettings/employeeSettings';
// @ts-ignore
import { handleGroupLog } from '#/api/task/index';
// @ts-ignore
import { SelectUsers } from '#/components/selectUsers';

// @ts-ignore
import { defautTableColumns, drawerFormSchema } from './config-data';

const emit = defineEmits<{ reload: [] }>();

const executorRef: any = ref(null);
const selectParams = ref({
  types: ['users'],
  userParams: {
    stationId: 0,
  },
});
const [ExecutorModal, executorModalApi] = useVbenModal({
  title: '选择负责人',
  width: 1000,
  height: 800,
  showCancelBtn: false,
  onConfirm: async () => {
    const users = await executorRef.value.confirmSelection();
    if (users?.length) {
      if (selectCount.value > 0 && users.length > selectCount.value) {
        // @ts-ignore
        ElMessage.error(`至多选择${selectCount.value}个人`);
        return;
      }

      // selectedUsers通过 id去重
      users.forEach((item: any) => {
        const index = selectedUsers.value.findIndex(
          (o: any) => o.id === item.id,
        );
        if (index === -1) {
          selectedUsers.value.push(item);
        }
      });

      basicTableApi.reload();
      selectUserCallback.value(users);
      executorModalApi.close();
    }
  },
});

// 处理选择人员按钮点击事件
const selectUserCallback = ref<Function>(() => {});
const selectCount = ref<number>(1);
const selectedUsers = ref<any[]>([]);
const handleClick = (count: number, event: Function) => {
  selectUserCallback.value = event;
  selectCount.value = count;
  executorModalApi.open();
};

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(handleClick),
});
// const isUpdateRef = ref<boolean>(false);
const taskParams = ref({
  taskId: '',
  taskName: '',
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen: any) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { taskId, taskName, stationId, taskList } = drawerApi.getData();
      taskParams.value.taskId = taskId;
      taskParams.value.taskName = taskName;
      formApi.setFieldValue('shiftLeaderId', taskList[0].executorId);
      formApi.setFieldValue('shiftLeaderName', taskList[0].executorIdName);
      selectParams.value.userParams.stationId = stationId;
    } catch (error) {
      console.error(error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  onClosed() {
    formApi.resetForm();
  },
  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      // 设置其他分工列表到表单值
      formApi.setFieldValue(
        'otherDivision',
        JSON.stringify(otherDivisionList.value),
      );

      const values = await formApi.getValues();
      // console.log('params', values);
      const params = {
        // ...formApi.getValues(),
        id: taskParams.value.taskId,
        ...values,
        evaluationRecords: [],
      };
      const otherDivision: any = [];
      otherDivisionList.value.forEach((item: any) => {
        if (item.content && item.id) {
          otherDivision.push({
            ...item,
            content: item.content.trim(),
          });
        }
      });

      // params.otherDivision = otherDivision;

      // 评价
      const evaluations = basicTableApi.grid.getData();

      evaluations.forEach((item: any) => {
        for (const key in item) {
          if (key.startsWith('id_')) {
            const info: any = {
              employeeId: item.employeeId,
              itemId: Number(key.replace('id_', '')),
              totalScore: Number(item[key] || 0),
              evaluationWords: item.evaluationWords,
            };
            params.evaluationRecords.push(info);
          }
        }
      });

      // console.log('params', params);
      await handleGroupLog(params);
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});

const gridOptions: VxeGridProps = {
  // 配置字体大小
  size: 'medium',
  // 配置表格右上角全屏、刷新
  toolbarConfig: {
    custom: false,
    refresh: false,
    zoom: false,
  },
  // 关闭分页
  pagerConfig: {
    enabled: false,
  },
  // 获取表格数据
  proxyConfig: {
    ajax: {
      query: async () => {
        return {
          items: selectedUsers.value.map((o: any) => {
            // @ts-ignore
            evaluationItems.value.forEach((item: string) => {
              o[item] = 0;
            });
            return {
              ...o,
              employeeId: o.id,
              employeeName: o.name,
            };
          }),
        };
      },
    },
  },
  // 配置显示列
  columns: [],
  editConfig: {
    mode: 'cell',
    trigger: 'click',
  },
};

const [BasicTable, basicTableApi] = useVbenVxeGrid({
  // formOptions,
  // gridOptions,
});

// 其他分工列表
const otherDivisionList = ref<any[]>([]);

// 添加其他分工
const addOtherDivision = () => {
  otherDivisionList.value.push({ id: '', name: '未选择', content: '' });
};

// 删除其他分工
const removeOtherDivision = (index: number) => {
  otherDivisionList.value.splice(index, 1);
};

// 选择其他分工负责人
const handleSelectOtherDivision = (index: number, users: any) => {
  if (users?.length) {
    otherDivisionList.value[index].id = users[0].id;
    otherDivisionList.value[index].name = users[0].name;
  }
};

const evaluationItems = ref<string[]>([]);

const init = async () => {
  const res: any = await employeeSettingsList({});
  // gridOptions.columns = [];
  gridOptions.columns = defautTableColumns;
  if (
    res.rows?.length &&
    !(gridOptions && gridOptions.columns && gridOptions.columns?.length > 1)
  ) {
    res.rows.forEach((item: any) => {
      evaluationItems.value.push(item.dictCode);
      // @ts-ignore
      gridOptions.columns.push({
        field: `id_${item.id}`,
        title: `${item.itemName}（${item.standardScore}）`,
        editRender: {
          name: 'input',
          immediate: true,
          defaultValue: 20,
        },
        slots: {
          edit: (data: any) => {
            return (
              <ElInputNumber
                controls-position="right"
                max={item.standardScore}
                min={0}
                precision={3}
                step={0.1}
                v-model={data.row[`id_${item.id}`]}
              />
            );
          },
        },
        width: 200,
      });
    });
    // @ts-ignore
    gridOptions.columns.push({
      field: 'evaluationWords',
      title: `评语`,
      editRender: { name: 'textarea' },
      // cellType: 'number',
      width: 200,
    });
  }

  basicTableApi.setGridOptions(gridOptions);
};

onMounted(async () => {
  await init();
  // gridOptions.columns = await tableColumns();
});
</script>

<template>
  <Drawer :title="taskParams.taskName">
    <Form>
      <template #evaluationComments>
        <BasicTable table-title="" class="w-full" />
      </template>

      <template #otherDivision>
        <div class="other-division-container">
          <div
            v-for="(item, index) in otherDivisionList"
            :key="index"
            class="mb-2 flex w-full items-center gap-2"
          >
            <ElInput
              v-model="item.content"
              placeholder="请输入分工内容"
              class="w-full flex-1"
            >
              <template #append>
                <div class="flex items-center gap-1">
                  <!-- <span></span> -->
                  <ElButton
                    size="small"
                    type="primary"
                    @click="
                      handleClick(1, (users: any) =>
                        handleSelectOtherDivision(index, users),
                      )
                    "
                  >
                    {{ item.name }}
                  </ElButton>
                </div>
              </template>
              <!-- <template #append>
                <ElButton
                  type="danger"
                  size="small"
                  @click="removeOtherDivision(index)"
                >
                  删除
                </ElButton>
              </template> -->
            </ElInput>
            <ElIcon
              class="ml-2 cursor-pointer"
              @click="removeOtherDivision(index)"
              color="red"
            >
              <Delete />
            </ElIcon>
          </div>
          <ElButton
            type="primary"
            size="small"
            @click="addOtherDivision"
            class="mt-2"
          >
            添加
          </ElButton>
        </div>
      </template>
    </Form>
    <ExecutorModal class="w-[700px]">
      <SelectUsers
        ref="executorRef"
        :user-params="selectParams.userParams"
        :only-users="true"
      />
    </ExecutorModal>
  </Drawer>
</template>
<style scoped lang="scss">
:deep(.el-input-number) {
  width: 100%;
}
</style>
