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

import {
  Input,
  Textarea,
  Select,
  RadioGroup,
  CheckboxGroup,
  DatePicker,
  Form,
  FormItem,
  Tag,
  ImagePreviewGroup,
  Image,
  Radio,
  message,
} from 'ant-design-vue';
import { InfoCircleOutlined, FormOutlined } from '@ant-design/icons-vue';
// import { ImageUpload, FileUpload } 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 } from '#/api/tasks/index';

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');
import { useVbenForm } from '#/adapter/form';
import { approvalTask, getTaskNodeSettings } from '#/api/processTask.js';
import ImageUpload from '#/views/common/form/components/ImageUpload.vue';
import FileUpload from '#/views/common/form/components/FileUpload.vue';
import type { PoliceCapacityForm } from '#/api/biz/policeCapacity/model';
import { getUserSign } from '#/api/org.js';
import { compressBase64Image } from '#/utils/imageUtil.js';
import SignPanel from '#/views/common/form/components/SignPanel.vue';
import { useUserStore } from '@vben/stores';

const userStore = useUserStore();

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


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

/**
 * 定义默认值 用于reset
 */
const defaultValues = {
  spjg: undefined,
  text: undefined,
  fileList: [],
  imageList: [],
  signature: '',
  updateSign: false,
};

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

type AntdFormRules<T> = Partial<Record<keyof T, RuleObject[]>> & {
  [key: string]: RuleObject[];
};
/**
 * 表单校验规则
 */
const formRules = ref<AntdFormRules<PoliceCapacityForm>>({
  spjg: [{ 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: '', //任务状态
  externSetting: {
    enableSign: false, //是否需要签名
  },
});

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

    // detailValue.value = modalApi.getData();

    const { instanceId, nodeId, taskId } = modalApi.getData();
    detailValue.value = await tasksDetail(instanceId, nodeId);
    detailValue.value.progress.forEach((item: any) => {
      if (item.user && item.user.name) {
        if (item.user.name == userName.value) {
          detailValue.value.taskId = item.taskId;
        }
      }
    });

    // detailValue.value.taskId = taskId;
    getTaskNodeSettings(detailValue.value.taskId)
      .then((rsp: any) => {
        isShowSign.value = rsp.data.enableSign || false;
      })
      .catch((e: any) => {
        message.error('获取节点设置失败');
      });

    // const record = await policeCapacityInfo(id);
    // 只赋值存在的字段
    // const filterRecord = pick(record, Object.keys(defaultValues));
    // formData.value = filterRecord;

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

// 获取任务详情
async function getTaksDetail(id: string | number, nodeId: string | number) {
  detailValue.value = await tasksDetail(id, nodeId);
}

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    await validate();
    // 可能会做数据处理 使用cloneDeep深拷贝
    const data = cloneDeep(formData.value);

    let params = {
      instanceId: detailValue.value.instanceId,
      taskId: detailValue.value.taskId,
      comment: {
        text: data.text,
        attachments: data.imageList.concat(data.fileList),
      },
      formData: {},
      signature: data.signature,
      // action: data.spjg == 1 ? 'agree' : 'refuse',
      action: data.spjg == 1 ? 'agree' : 'recall',
      updateSign: data.updateSign,
      targetNode: data.spjg == 1?null:'root',
      targetUser: null,
      otherNodeUsers: {},
    };
    if (isShowSign.value && !data.signature && data.spjg != 1) {
      message.error('请签字后再提交');
      return;
    }


    // return;

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

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

function loadBeforeSign() {
  getUserSign().then((rsp: any) => {
    if (rsp.data === '') {
      message.warning('您还没有保存过的签名');
    } else {

      formData.value.signature = rsp.data;
    }
  });
}
</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">
            <Tag color="#006be6" v-if="detailValue.status === '审批进行中'"
              >审批进行中</Tag
            >
            <Tag color="#87d068" v-else>审批通过</Tag>
          </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
                style="margin-right: 10px;"
                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
              target="_blank"
              :href="item.url"
              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">
          <RadioGroup v-model:value="formData.spjg">
            <Radio :value="1">通过</Radio>
            <Radio :value="2">退回</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="审批意见" v-bind="validateInfos.text">
          <Textarea
            v-model:value="formData.text"
            placeholder="请输入审批意见"
            :auto-size="{ minRows: 2, maxRows: 6 }"
          ></Textarea>
        </FormItem>
        <div class="action-content">
          <image-upload
            class="image-upload"
            v-model="formData.imageList"
            placeholder="添加图片"
            :max-size="10"
            :max-number="10"
            mode="PC"
          />
          <file-upload
            v-model="formData.fileList"
            placeholder="添加附件"
            :max-size="100"
            :max-number="5"
            mode="PC"
          />
        </div>
        <div v-if="isShowSign">
          <el-divider>签字</el-divider>
          <sign-panel mode="PC" v-model="formData.signature" />
          <div>
            <el-button
              link
              type="primary"
              style="margin-right: 30px"
              @click="loadBeforeSign"
              >使用上次签名</el-button
            >
            <el-checkbox v-model="formData.updateSign"
              >保存本次签名</el-checkbox
            >
          </div>
        </div>
      </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>
