<!--
 * @Author: Mm
 * @Date: 2025-05-16 10:07:50
 * @LastEditors: Mm
 * @LastEditTime: 2025-06-10 17:07:56
 * 不写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,
  doXiaFaMJ,
} from '#/api/tasks/index';
import {
  taskWorkInfo,
} from '#/api/tasks/work';
import {
  getDeptTree,
  listUserByDeptId
} 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 userValue = ref<string[]>([]);

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

/**
 * 定义默认值 用于reset
 */
const defaultValues = {
  content: undefined,
  zxrwfj: undefined,
  ossId: undefined,
};

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

/**
 * 表单校验规则
 */
const formRules = ref({
  content: [{ required: true, message: '协作任务描述不能为空' }],
  text: [{ required: true, message: '审批意见不能为空' }],
  userValue: [{ 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 workDetail = ref<any>({
  id: null,
  capacityId: null,
  deptId: "",
  deptName: "",
  ossId: '',
  sponsorId: '',
  sponsorName: '',
  status: "0",
  taskNo: "",
  workContent: ""
});
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, deptId, workId } = modalApi.getData();
    taskNo.value = instanceId;
    detailValue.value = await tasksDetail(instanceId, nodeId);
    workDetail.value  = await taskWorkInfo(workId);
    // 有协作信息带过来 让他重新修改
    if (workDetail.value){
      formData.value.content = workDetail.value.workContent;
      formData.value.ossId = workDetail.value.ossList

      console.log(formData.value.ossId, 'formData.value.ossId');
    }
    userData.value = await listUserByDeptId(deptId);

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



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

    // 可能会做数据处理 使用cloneDeep深拷贝
    const data: any = cloneDeep(formData.value);

    data.id = workDetail.value.id;
    data.ossId = data.ossId?.map((item: string) => Number(item));
    data.taskNo = taskNo.value;
    data.sponsorId = userValue.value;
    await doXiaFaMJ(data);

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

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

</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.userValue">
          <Select
            v-model:value="userValue"
            :options="userData"
            style="width: 100%"
            :showSearch="true"
            optionFilterProp="nickName"
            placeholder="请选择协作民警"
            :fieldNames="replaceFields"
          >
          </Select>
        </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>
