<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="980px"
    :visible="visible"
    :confirm-loading="loading"
    :maxable="maxAble"
    :title="isUpdate ? '编辑工单' : '添加工单'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    :maskClosable="false"
    @ok="save"
  >
    <a-form
      :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
      :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
      layout="vertical"
    >
      <a-form-item label="工单名称" v-bind="validateInfos.name">
        <a-input
          allow-clear
          :maxlength="20"
          placeholder="请输入工单名称"
          v-model:value="form.name"
          @blur="validate('name', { trigger: 'blur' }).catch(() => {})"
        />
      </a-form-item>
      <a-form-item label="工单内容" v-bind="validateInfos.content">
        <!-- 编辑器 -->
        <byte-md-editor
          v-model:value="content"
          placeholder="请输入您的工单内容，图片请直接粘贴"
          :locale="zh_Hans"
          :plugins="plugins"
          height="300px"
          :editorConfig="{ lineNumbers: true }"
          @paste="onPaste"
        />
      </a-form-item>
      <a-row :gutter="16">
        <a-col :md="12" :sm="24" :xs="24">
          <a-form-item label="工单类型" v-bind="validateInfos.taskType">
            <a-select
              optionFilterProp="label"
              placeholder="请选择工单类型"
              :options="taskType"
              allow-clear
              v-model:value="form.taskType"
            />
          </a-form-item>
<!--          <a-form-item label="指派给" v-bind="validateInfos.commander">-->
<!--            <SelectStaff v-model:value="commander" @done="onCommander" />-->
<!--          </a-form-item>-->
          <a-form-item label="发起人" v-bind="validateInfos.promoter">
            <SelectCompany v-model:value="promoter" @done="onPromoter" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24" :xs="24">
          <a-form-item label="关联应用(选填)" v-bind="validateInfos.appId">
            <SelectApp v-model:value="appId" @done="onApp" />
          </a-form-item>
<!--          <a-form-item label="品质要求" v-bind="validateInfos.quality">-->
<!--            <a-select-->
<!--              optionFilterProp="label"-->
<!--              placeholder="请选择品质要求"-->
<!--              :options="quality"-->
<!--              allow-clear-->
<!--              v-model:value="form.quality"-->
<!--            />-->
<!--          </a-form-item>-->
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :md="12" :sm="24" :xs="24">
          <a-form-item label="上传附件" v-bind="validateInfos.files">
            <a-upload
              v-model:file-list="fileList"
              class="upload-list-inline"
              list-type="picture"
              :before-upload="beforeUpload"
            >
              <a-button>
                <UploadOutlined />
                上传附件
              </a-button>
            </a-upload>
<!--            <ele-image-upload-->
<!--              v-model:value="files"-->
<!--              :limit="9"-->
<!--              :drag="true"-->
<!--              :multiple="true"-->
<!--              :upload-handler="uploadHandler"-->
<!--              @upload="onUpload"-->
<!--            />-->
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24" :xs="24">
<!--          <a-form-item label="优先级" v-bind="validateInfos.priority">-->
<!--            <a-select-->
<!--              optionFilterProp="label"-->
<!--              placeholder="请选择优先级"-->
<!--              :options="priority"-->
<!--              allow-clear-->
<!--              v-model:value="form.priority"-->
<!--            />-->
<!--          </a-form-item>-->
        </a-col>
      </a-row>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
import {ref, reactive, watch, computed} from 'vue';
import {Form, message, Modal, SelectProps} from 'ant-design-vue';
import {useUserStore} from '@/store/modules/user';
import {assignObject, htmlToText} from 'ele-admin-pro';
import type {Task} from '@/api/oa/task/model';
import {addTask, updateTask} from '@/api/oa/task';
import {FILE_SERVER} from "@/config/setting";
import {uploadFile} from "@/api/system/file";
import {RuleObject} from "ant-design-vue/es/form";
import { getDictionaryOptions, isImage, selectProject } from "@/utils/common";
import SelectStaff from '@/components/SelectStaff/index.vue';
import SelectCompany from '@/components/SelectCompany/index.vue';
import SelectApp from '@/components/SelectApp/index.vue';
import 'bytemd/dist/index.min.css';
import highlight from '@bytemd/plugin-highlight-ssr'
import 'highlight.js/styles/default.css'
import ByteMdEditor from '@/components/ByteMdEditor/index.vue';
// import highlight from '@bytemd/plugin-highlight';
// 中文语言文件
import zh_Hans from 'bytemd/locales/zh_Hans.json';
// 链接、删除线、复选框、表格等的插件
import gfm from '@bytemd/plugin-gfm';
// 插件的中文语言文件
import zh_HansGfm from '@bytemd/plugin-gfm/locales/zh_Hans.json';
import { ItemType } from "ele-admin-pro/es/ele-image-upload/types";
import { UploadOutlined } from '@ant-design/icons-vue';

const useForm = Form.useForm;
const props = defineProps<{
  // 弹窗是否打开
  visible: boolean;
  // 修改回显的数据
  data?: Task | null;
}>();

const userStore = useUserStore();
// 当前登录用户信息
const loginUser = computed(() => userStore.info ?? {});
// 是否是修改
const isUpdate = ref(false);
const disabled = ref(false);
// 是否显示最大化切换按钮
const maxAble = ref(true);
// 选项卡位置
const activeKey = ref('1');
const promoter = ref<any>(undefined);
const commander = ref(undefined);
const appid = ref(undefined);
// 字典数据
const taskType = getDictionaryOptions('taskType');
const progress = getDictionaryOptions('taskProgress');
const priority = getDictionaryOptions('taskPriority');
const quality = getDictionaryOptions('taskQuality');
/* 打开选择弹窗 */
const showUser = ref(false);
const showProject = ref(false);
const content = ref('');
const files = ref<ItemType[]>([]);
const fileList = ref<ItemType[]>([]);


const emit = defineEmits<{
  (e: 'done'): void;
  (e: 'update:visible', visible: boolean): void;
}>();
// 已上传数据, 可赋初始值用于回显
const avatar = ref(<any>[]);
// 提交状态
const loading = ref(false);
// 用户信息
const form = reactive<Task>({
  // 工单名称
  name: '',
  appId: undefined,
  // 工单类型
  taskType: '普通工单',
  // 项目ID
  projectId: '',
  // 客户ID
  customerId: '',
  // 资产ID
  assetsId: '',
  // 开始时间
  startTime: '',
  // 结束时间
  endTime: '',
  // 工单内容
  content: '',
  // 工单发起人
  promoter: undefined,
  // 负责人
  commander: undefined,
  // 工单状态
  progress: 0,
  // 优先级
  priority: '中',
  // 品质要求
  quality: 'B级',
  // 期限(天)
  day: '',
  files: '',
  // 排序
  sortNumber: 100,
  // 备注
  comments: '',
  // 创建时间
  createTime: '',
  // 状态
  status: 0,
  // 发布者
  userId: undefined
});

/* 更新visible */
const updateVisible = (value: boolean) => {
  emit('update:visible', value);
};

// 表单验证规则
const rules = reactive({
  name: [
    {
      required: true,
      type: 'string',
      message: '请输入工单名称',
      trigger: 'blur'
    }
  ],
  taskType: [
    {
      required: true,
      type: 'string',
      message: '请选择工单类型',
      trigger: 'blur'
    }
  ],
  // promoter: [
  //   {
  //     required: true,
  //     type: 'number',
  //     message: '请选择发起人',
  //     trigger: 'blur',
  //     validator: async (_rule: RuleObject, value: number) => {
  //       if (promoter.value == undefined) {
  //         return Promise.reject('请选择发起人');
  //       }
  //       return Promise.resolve();
  //     }
  //   }
  // ],
  // commander: [
  //   {
  //     required: true,
  //     type: 'number',
  //     message: '请选择受理人',
  //     trigger: 'blur',
  //     validator: async (_rule: RuleObject, value: number) => {
  //       if (commander.value == undefined) {
  //         return Promise.reject('请选择受理人');
  //       }
  //       return Promise.resolve();
  //     }
  //   }
  // ],
  content: [
    {
      required: true,
      type: 'string',
      message: '请输入工单内容',
      trigger: 'blur',
      validator: async (_rule: RuleObject, value: string) => {
        if (content.value == '') {
          return Promise.reject('请输入文字内容');
        }
        return Promise.resolve();
      }
    }
  ]
});

const onPromoter = (userId) => {
  promoter.value = userId
}

const onCommander = (userId) => {
  commander.value = userId
}

const onApp = (appId) => {
  appid.value = appId
}

/* 图片上传事件 */
const uploadHandler = (file: File) => {
  const item: ItemType = {
    file,
    uid: (file as any).uid,
    name: file.name
  };
  if (!file.type.startsWith("image")) {
    message.error("只能选择图片");
    return;
  }
  if (file.size / 1024 / 1024 > 2) {
    message.error("大小不能超过 2MB");
    return;
  }
  onUpload(item);
};

// 文件上传事件
const beforeUpload = (file: File) => {
  const item: ItemType = {
    file,
    uid: (file as any).uid,
    name: file.name
  }
  if (!file.type.startsWith("image")) {
    if (file.size / 1024 / 1024 > 100) {
      message.error("大小不能超过 100MB");
      return;
    }
  }
  onUpload(item);
  return false;
};

const onUpload = (d: ItemType) => {
  console.log(d);
  uploadFile(<File>d.file)
    .then((result) => {
      files.value.push({
        uid: result.id,
        url: FILE_SERVER + result.path,
        name: isImage(result.path) ? 'image' : result.name,
        status: "done"
      });
      message.success("上传成功");
    })
    .catch((e) => {
      message.error(e.message);
    });
};

const {resetFields, validate, validateInfos} = useForm(form, rules);

/* 保存编辑 */
const save = () => {
  validate()
    .then(() => {
      loading.value = true;
      const data = {
        ...form,
        // 处理工单内容
        content: content.value,
        appId: appid.value,
        promoter: promoter.value,
        commander: commander.value,
        files: JSON.stringify(files.value)
      };
      // 转字符串
      const saveOrUpdate = isUpdate.value ? updateTask : addTask;
      saveOrUpdate(data)
        .then((msg) => {
          loading.value = false;
          content.value = '';
          message.success(msg);
          updateVisible(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          message.error(e.message);
        });
    })
    .catch(() => {
    });
};

// 插件
const plugins = ref([
  gfm({
    locale: zh_HansGfm
  }),
  highlight()
]);

/* 粘贴图片上传服务器并插入编辑器 */
const onPaste = (e) => {
  console.log(e);
  const items = (e.clipboardData || e.originalEvent.clipboardData).items;
  console.log(items);
  let hasFile = false;
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf('image') !== -1) {
      let file = items[i].getAsFile();
      const item: ItemType = {
        file,
        uid: (file as any).lastModified,
        name: file.name
      };
      uploadFile(<File>item.file)
        .then((result) => {
          const addPath = '!['+result.name+']('+FILE_SERVER + result.path+')\n\r';
          content.value = content.value + addPath
        })
        .catch((e) => {
          message.error(e.message);
        });
      hasFile = true;
    }
  }
  if (hasFile) {
    e.preventDefault();
  }
}

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      if (props.data) {
        loading.value = false;
        assignObject(form, props.data);
        // 头像赋值
        avatar.value = [];
        if (props.data.images) {
          avatar.value.push({uid: 1, url: FILE_SERVER + props.data.images, status: ''});
        }
        if (props.data.content) {
          content.value = props.data.content;
        }

        form.sortNumber = Number(props.data.sortNumber);
        isUpdate.value = true;
      } else {
        content.value = '';
        avatar.value = [];
        isUpdate.value = false;
      }
    } else {
      resetFields();
    }
  }
);

</script>
<style lang="less">
.tab-pane {
  min-height: 300px;
}

.form-item-help {
  font-size: 12px;
  // line-height: 2;
  line-height: 1.5;
  padding-top: 4px;
  min-height: 22px;
  // margin-top: -2px;
  transition: color 0.3s cubic-bezier(0.215, 0.61, 0.355, 1);

  a {
    margin: 0 3px;
  }

  .extra,
  small {
    color: rgba(0, 0, 0, 0.45);
    font-size: 12.5px !important;
  }

  .extra {
    margin-bottom: 4px !important;
  }
}

.select-shop {
  min-width: 120px;
  margin-right: 20px;
}
.upload-list-inline :deep(.ant-upload-list-item) {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.upload-list-inline [class*='-upload-list-rtl'] :deep(.ant-upload-list-item) {
  float: right;
}
</style>
