<!--
 * @Author: Mm
 * @Date: 2025-05-16 10:07:50
 * @LastEditors: Mm
 * @LastEditTime: 2025-06-10 16:08:49
 * 不写bug的程序员不是一个好程序员!
-->
<!--
使用antd原生Form生成 详细用法参考ant-design-vue Form组件文档
vscode默认配置文件会自动格式化/移除未使用依赖
-->
<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';
import { computed, onMounted, ref } from 'vue';

import {
  Input,
  Textarea,
  Select,
  RadioGroup,
  CheckboxGroup,
  DatePicker,
  Form,
  FormItem,
  Tag,
  ImagePreviewGroup,
  Image,
  Radio,
  Table,
  message,
  TreeSelect,
} from 'ant-design-vue';
import { InfoCircleOutlined, FormOutlined } from '@ant-design/icons-vue';
import { ImageUpload, FileTzUpload } from '#/components/upload';
import { Tinymce } from '#/components/tinymce';
import { getPopupContainer } from '@vben/utils';
import { pick } from 'lodash-es';

import { getDictOptions } from '#/utils/dict';
import {
  tasksDetail,
  xzdTreesList,
  jznlFzrList,
  doQingzhiXiaFa,
} from '#/api/tasks/index';
import {
  getDeptTree
} from '#/api/system/user';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { DictTag } from '#/components/dict';
const dictInfo = getDictOptions('tasks_type');
const dictStatus = getDictOptions('biz_task_status');

import { useVbenForm } from '#/adapter/form';

import { useUserStore } from '@vben/stores';

const userStore = useUserStore();

const userName = computed(() => {
  return userStore.userInfo?.username;
});

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

// 协作能力树选择器value
const deptValue = ref<string[]>([]);

const replaceFields = {
  children: 'children',
  label: 'label',
  value: 'id',
};
const deptTreeData = ref<any>([]); //协作能力树结构数据

/**
 * 定义默认值 用于reset
 */
 interface DeptItem {
  deptId: string;
  deptName: string;
}
const defaultValues = {
  content: undefined,
  zxrwfj: undefined,
  ossId: undefined,
  depts:[] as DeptItem[]
};

/**
 * 表单数据ref
 */
const formData = ref(defaultValues);

/**
 * 表单校验规则
 */
const formRules = ref({
  content: [{ required: true, message: '协作任务描述不能为空' }],
  text: [{ required: true, message: '审批意见不能为空' }],
});

/**
 * useForm解构出表单方法
 */
const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);
const detailValue = ref<any>({
  formData: {
    field4997982661951: '', //任务名称
    field9166682677829: ['1'], //任务类型
    field4812283627149: '', //任务内容
    field4385824969331: [], //文件
    field3232724933592: [], //图片
  },
  staterUser: {}, //发起人
  startTime: '', //发起时间
  starterDept: '', //发起人部门
  status: '', //任务状态

  bizStatus: '-1',
});
const taskNo = ref('');
const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[1050px]',
  fullscreenButton: false,
  closeOnClickModal: false,
  onClosed: handleCancel,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);


    const { instanceId, nodeId, taskId } = modalApi.getData();
    taskNo.value = instanceId;
    detailValue.value = await tasksDetail(instanceId, nodeId);
    deptTreeData.value = await getDeptTree();
    // const record = await policeCapacityInfo(id);
    // 只赋值存在的字段
    // const filterRecord = pick(record, Object.keys(defaultValues));
    // formData.value = filterRecord;

    modalApi.modalLoading(false);
  },
});



async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    await validate();

    // 可能会做数据处理 使用cloneDeep深拷贝
    const data: any = cloneDeep(formData.value);
    data.ossId = data.ossId?.map((item: string) => Number(item));
    data.taskNo = taskNo.value;

    await doQingzhiXiaFa(data);

    emit('reload');
    await handleCancel();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleCancel() {
  modalApi.close();
  formData.value = defaultValues;
  resetFields();
}

// 遍历树结构查找节点
function findNodeInTree(tree: any, value: any) {
  for (const node of tree) {
    if (node.id === value) {
      return node;
    }
    if (node.children) {
      const found: any = findNodeInTree(node.children, value);
      if (found) return found;
    }
  }
  return null;
}
// 如果是多选模式 (multiple)，则可以这样处理多个值：
function getSelectedNodes(tree: any, values: any) {
  return values
    .map((value: any) => findNodeInTree(tree, value))
    .filter(Boolean);
}

const groupedNodes = ref<any>([]); // 存储选中的完整节点

async function handleSelect(value: any) {
  if (!value.length) {
    formData.value.depts = [];
    return;
  }
  var deptids:any = [];
  value.forEach(function(item:any){
    deptids.push({deptId: item, deptName:''});
  });
  formData.value.depts = deptids;
}

function groupByDept(nodes: any, optionsMap: Record<string, any[]>) {
  const map = new Map();
  const result = [];

  for (const node of nodes) {
    const key = `${node.deptId}-${node.deptName}`;

    if (!map.has(key)) {
      map.set(key, {
        deptName: node.deptName,
        deptId: node.deptId,
        childrenGroups: [],
        capacityIds: [],
        jznlStr: '',
        userId: undefined,
        roleKey: 'hezhanzhongxin',
        options: optionsMap[node.deptId] || [], // 从传入的 optionsMap 获取
      });
    }

    const group = map.get(key);
    group.childrenGroups.push({
      id: node.id,
      name: node.name,
    });

    group.capacityIds.push(node.id);
    group.jznlStr = ''; // 初始化为空，后面统一赋值
  }

  // 最终处理 jznlStr
  for (const value of map.values()) {
    value.jznlStr = value.childrenGroups.map((c: any) => c.name).join(',');
    result.push(value);
  }

  return result;
}
</script>

<template>
  <BasicModal title="分配协作单位任务">
    <div class="card bg-blue">
      <div class="title">
        <InfoCircleOutlined />
        <span>任务信息</span>
      </div>
      <div class="itemWrap">
        <div class="item">
          <div class="item-label">任务标题:</div>
          <div class="item-value">
            {{ detailValue.formData.field4997982661951 }}
          </div>
        </div>
        <div class="item">
          <div class="item-label">任务类型:</div>
          <div class="item-value">
            <DictTag
              :dicts="dictInfo"
              :value="detailValue.formData.field9166682677829[0]"
            ></DictTag>
          </div>
        </div>
        <div class="item">
          <div class="item-label">发起人:</div>
          <div class="item-value">{{ detailValue.staterUser.name }}</div>
        </div>
        <div class="item">
          <div class="item-label">发起单位:</div>
          <div class="item-value">{{ detailValue.starterDept }}</div>
        </div>
        <div class="item">
          <div class="item-label">发起时间:</div>
          <div class="item-value">{{ detailValue.startTime }}</div>
        </div>
        <div class="item">
          <div class="item-label">当前状态:</div>
          <div class="item-value">
            <DictTag
              :dicts="dictStatus"
              :value="detailValue.bizStatus"
            ></DictTag>
          </div>
        </div>
        <div style="color: rgb(107 114 128); margin-bottom: 7px">任务内容:</div>
        <Textarea
          readonly
          v-model:value="detailValue.formData.field4812283627149"
          placeholder="任务内容"
          :auto-size="{ minRows: 2, maxRows: 6 }"
        />
        <div style="display: flex; flex-direction: column">
          <div
            v-if="
              detailValue.formData?.field3232724933592 ||
              detailValue.formData?.field4385824969331
            "
            style="
              color: rgb(107 114 128);
              margin-bottom: 7px;
              margin-top: 15px;
            "
          >
            任务附件:
          </div>
          <div class="imgs" v-if="detailValue.formData.field3232724933592">
            <ImagePreviewGroup>
              <Image
                v-for="item in detailValue.formData.field3232724933592"
                :key="item.id"
                :height="100"
                :src="item.url"
              />
            </ImagePreviewGroup>
          </div>
          <div
            class="files flex-column"
            v-if="detailValue.formData?.field4385824969331"
          >
            <a
              :href="item.url"
              target="_blank"
              v-for="item in detailValue.formData.field4385824969331"
              :key="item.id"
              >{{ item.name }}</a
            >
          </div>
        </div>
      </div>
    </div>
    <div class="card">
      <div class="title">
        <FormOutlined />
        <span>分配协作信息</span>
      </div>
      <Form layout="vertical">
        <FormItem label="协作单位" v-bind="validateInfos.spjg">
          <TreeSelect
            show-search
            style="width: 100%"
            v-model:value="deptValue"
            @change="handleSelect"
            :fieldNames="replaceFields"
            :tree-data="deptTreeData"
            placeholder="请选择协作单位"
            tree-checkable
            allow-clear
            multiple
            tree-default-expand-all
          />
        </FormItem>

        <FormItem label="协作任务描述" v-bind="validateInfos.content">
          <Textarea
            v-model:value="formData.content"
            placeholder="请输入协作任务描述"
            :auto-size="{ minRows: 4, maxRows: 7 }"
          ></Textarea>
        </FormItem>
        <FormItem label="协作任务附件">
          <FileTzUpload
            resultField="ossId"
            :multiple="true"
            :max-number="20"
            v-model:value="formData.ossId"
            :max-size="50"
          />
        </FormItem>
      </Form>
    </div>
  </BasicModal>
</template>
<style lang="scss" scoped>
.card {
  padding: 1rem;
  border-radius: 8px;
  border: 1px solid rgb(229 231 235);
  &:last-child {
    margin-top: 20px;
  }
  .title {
    font-size: 16px;
    margin-bottom: 15px;
    span:last-child {
      margin-left: 6px;
      letter-spacing: 1px;
    }
  }
}
.bg-blue {
  background-color: rgb(239 246 255);
  border: 1px solid rgb(219 234 254);
  .title {
    color: rgb(30 64 175);
    font-size: 16px;
    margin-bottom: 15px;
    span:last-child {
      margin-left: 6px;
      letter-spacing: 1px;
    }
  }
  .itemWrap {
    display: flex;
    width: 100%;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    .item {
      width: 48%;
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      .item-label {
        width: 80px;
        color: rgb(107 114 128);
      }
      .item-value {
        flex: 1;
        color: rgb(17 24 39);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}
.flex-column {
  display: flex;
  flex-direction: column;
}
.imgs {
  display: flex;
  flex-wrap: wrap;
}
.files {
  margin-top: 10px;
  a {
    font-size: 14px;
    margin-bottom: 5px;
    &:hover {
      color: #409eff;
    }
  }
}

.action-content {
  margin-top: 20px;
  img {
    border: 1px solid #dcdfe6;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 20px;
    &:hover {
      border: 1px dashed #409eff;
    }
  }
  :deep(.el-upload__input) {
    display: none;
  }
  :deep(.image-upload) {
    margin-bottom: 20px;
    .el-upload-list__item,
    .el-upload--picture-card {
      height: 65px;
      width: 65px;
    }
    .el-upload--picture-card {
      line-height: 70px;
    }
  }
}
</style>
