<template>
  <!-- 新增 -->
  <a-modal
    :width="700"
    :maskClosable="false"
    :visible="visible"
    :confirm-loading="loading"
    :forceRender="true"
    :title="isUpdate ? '编辑流程模型' : '新增流程模型'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
    style="top: 40px"
    @close="updateVisible(false)"
  >
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="图标：">
            <ModelIcons :url="activeIconSrc" @click="iconClick" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="模型名称：" name="modelName">
            <a-input v-model:value="form.modelName" placeholder="请填写模型名称" allow-clear autocomplete="off" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="模型编码：" name="modelCode">
            <a-input v-model:value="form.modelCode" placeholder="请填写模型编码" allow-clear autocomplete="off" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="模型分类：" name="businessCategoryId">
            <a-select v-model:value="form.businessCategoryId" style="width: 100%" placeholder="请选择模型分类">
              <a-select-option
                :value="item.businessCategoryId"
                v-for="(item, index) in categoryList"
                :key="index"
                :title="item.categoryName"
                >{{ item.categoryName }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="排序：" name="fldSort">
            <a-input-number
              v-model:value="form.fldSort"
              :min="0"
              style="width: 100%"
              placeholder="请输入排序"
              allow-clear
              autocomplete="off"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="流程管理员">
            <a-input
              v-model:value="form.managerUserIdWrapper"
              @focus="managerUserIdFocus"
              placeholder="请选择流程管理员"
              allow-clear
              autocomplete="off"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="描述：">
            <a-textarea v-model:value="form.remark" placeholder="请输入描述" :rows="4" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <a-modal :visible="visibleIcon" width="620px" title="选择图标" @ok="iconOk" @cancel="visibleIcon = false">
      <div class="type-icon">
        <a-radio-group v-model:value="form.modelIconType">
          <a-radio :value="1">自定义上传</a-radio>
          <a-radio :value="2">选择图片</a-radio>
        </a-radio-group>
      </div>
      <div v-if="form.modelIconType == 2">
        <img
          v-for="(icon, index) in iconList"
          :key="index"
          :src="icon.url"
          class="flow-icon-item"
          :class="{ active: selectedIcon === icon.name_suffix }"
          @click="selectedIconClick(icon)"
        />
      </div>
      <div v-if="form.modelIconType == 1">
        <a-upload
          name="file"
          :multiple="false"
          v-model:file-list="selectIconList"
          :default-file-list="selectIconList"
          :maxCount="1"
          :action="iconAddress.fileUploadUrl"
          list-type="picture-card"
          :headers="iconAddress.headers"
          :before-upload="beforeUpload"
          accept=".jpeg,.jpg,.png,.tif,.jfif,.webp,.pjp,.apng,.pjpeg,.avif,.ico,.tiff,.bmp,.xbm,.jxl,.jpeg,.svgz,.gif,.svg"
          @preview="handlePreviewPhoto"
          @download="downloadPhoto"
          @change="info => handleFileChange(info, 'selectIconList')"
          :showUploadList="{
            showDownloadIcon: true
          }"
        >
          <plus-outlined style="font-size: 28px; font-weight: 200" v-if="selectIconList.length == 0" />
        </a-upload>
      </div>
    </a-modal>

    <!-- 选择管理员 -->
    <Selection
      v-model:visible="visibleFlowPick"
      v-if="visibleFlowPick"
      :data="selectedData"
      :showTab="['user']"
      title="选择流程管理员"
      @done="closeFlowPick"
    ></Selection>

    <!-- 图标预览弹框 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </a-modal>
</template>

<script setup name="ModelAddEdit">
import { onMounted, reactive, ref, computed } from 'vue';
import { message, Upload } from 'ant-design-vue';
import ModelIcons from './model-icon.vue';
import { getToken } from '@/utils/token-util';
import { API_BASE_PREFIX } from '@/config/setting';
import { FileApi, FileUploadUrl as fileUploadUrlPrefix } from '@/views/system/backend/file/api/FileApi';
import { FlowModelApi } from '../api/FlowModelApi';
import { deepClone, getBusinessMaxSort } from '@/utils/common/util';
import { BusinessCategoryApi } from '../../../app/list/api/BusinessCategoryApi';

const props = defineProps({
  visible: Boolean,
  // 当前行数据
  data: Object,
  // 图标列表
  iconList: Array,
  // 分类id
  businessCategoryId: String
});

const emits = defineEmits(['done', 'update:visible']);

const loading = ref(false);
// 是否是编辑状态
const isUpdate = ref(false);
// 表单数据
const form = ref({
  formModelIds: [],
  businessCategoryId: props.businessCategoryId,
  modelIconType: 2,
  iconList: []
});
//是否显示选择图标弹框
const visibleIcon = ref(false);
// 验证规则
const rules = reactive({
  businessCategoryId: [{ required: true, message: '请输入模型分类', type: 'string', trigger: 'change' }],
  modelName: [{ required: true, message: '请输入模型名称', type: 'string', trigger: 'blur' }],
  modelCode: [{ required: true, message: '请输入模型编码', type: 'string', trigger: 'blur' }],
  fldSort: [{ required: true, message: '请输入排序', type: 'number', trigger: 'blur' }]
});
// ref
const formRef = ref(null);
// 当前激活图标
const activeIcon = ref(null);
// 当前选中图标
const selectedIcon = ref(null);

// 分类列表
const categoryList = ref([]);

// 是否显示选择人员弹框
const visibleFlowPick = ref(false);

// 总数据
const selectedData = ref({
  selectUserList: []
});

// 是否展示图片预览
const previewVisible = ref(false);
// 图片地址
const previewImage = ref(null);

// 图标上传预览地址
const iconAddress = reactive({
  // 上传文件的url
  fileUploadUrl: `${API_BASE_PREFIX}${fileUploadUrlPrefix}?secretFlag=N`,
  filePreviewUrl: `${API_BASE_PREFIX}/sysFileInfo/public/preview?fileId=`,
  // 上传文件时候要带header
  headers: {
    Authorization: getToken()
  }
});

// 选中的图标列表
const selectIconList = ref([]);

/**
 * 图标
 */
const activeIconSrc = computed(() => {
  const icon = props.iconList.find(t => t.name_suffix == activeIcon.value);
  if (form.value.modelIconType == 2) {
    return icon ? icon.url : '';
  } else {
    let fileId = '';
    if (form.value.iconList?.length > 0) {
      fileId = form.value.iconList[0]?.response?.data?.fileId
        ? form.value.iconList[0]?.response?.data?.fileId
        : form.value.iconList[0]?.uid;
    }
    return iconAddress.filePreviewUrl + fileId;
  }
});

onMounted(async () => {
  getCategoryData();
  if (props.data) {
    isUpdate.value = true;
    getDetail();
  } else {
    isUpdate.value = false;
    activeIcon.value = props.iconList[0].name_suffix;
    selectedIcon.value = props.iconList[0].name_suffix;
    form.value.modelIcon = props.iconList[0].name_suffix;
    form.value.fldSort = await getBusinessMaxSort('FLOW_DESIGN_MODEL');
  }
});

// 获取详情
const getDetail = () => {
  FlowModelApi.detail({ modelId: props.data.modelId }).then(res => {
    form.value = Object.assign({}, res.data);
    activeIcon.value = form.value.modelIcon;
    selectedIcon.value = form.value.modelIcon;
    if (!form.value.modelIconType) {
      form.value.modelIconType = 2;
    }

    form.value.iconList = [];
    if (res.data?.modelIconFileId) {
      setFileList('iconList', res.data.modelIconFileId);
    }
  });
};

// 设置文件列表
const setFileList = (name, fileId) => {
  FileApi.getAntdVInfo({ fileId: fileId }).then(res => {
    res.uid = fileId;
    form.value[name] = [res];
  });
};

// 获取分类列表
const getCategoryData = () => {
  loading.value = true;
  BusinessCategoryApi.list()
    .then(res => {
      categoryList.value = res;
    })
    .finally(() => (loading.value = false));
};

// 更改弹框或抽屉状态
const updateVisible = value => {
  emits('update:visible', value);
};

// 选择图标
const iconClick = () => {
  selectIconList.value = deepClone(form.value.iconList);
  visibleIcon.value = true;
};

// 图标点击
const selectedIconClick = icon => {
  selectedIcon.value = icon.name_suffix;
  iconOk();
};

//   关闭选择图标弹框
const iconOk = () => {
  if (form.value.modelIconType == 1) {
    if (selectIconList.value.length == 0) return message.warning('请上传一个图标');
    form.value.iconList = deepClone(selectIconList.value);
  } else {
    activeIcon.value = selectedIcon.value;
    form.value.modelIcon = selectedIcon.value;
  }
  visibleIcon.value = false;
};

// 点击确定
const save = async () => {
  await formRef.value.validate();

  if (form.value.modelIconType == 1) {
    form.value.modelIcon = '';
    if (form.value.iconList?.length) {
      form.value.modelIconFileId = form.value.iconList[0]?.response?.data?.fileId
        ? form.value.iconList[0]?.response?.data?.fileId
        : form.value.iconList[0]?.uid;
    }
  } else {
    form.value.modelIconFileId = '';
  }
  // 修改加载框为正在加载
  loading.value = true;

  let result = null;

  // 执行编辑或修改
  if (isUpdate.value) {
    result = FlowModelApi.edit(form.value);
  } else {
    result = FlowModelApi.add(form.value);
  }
  result
    .then(result => {
      // 移除加载框
      loading.value = false;

      // 提示添加成功
      message.success(result.message);
      form.value = {};
      // 关闭弹框，通过控制visible的值，传递给父组件
      updateVisible(false);

      // 触发父组件done事件
      emits('done');
    })
    .catch(() => {
      loading.value = false;
    });
};

// 流程管理员选择
const managerUserIdFocus = () => {
  const { managerUserId, managerUserIdWrapper } = form.value;
  if (managerUserId && managerUserIdWrapper) {
    selectedData.value.selectUserList = [{ bizId: managerUserId, name: managerUserIdWrapper }];
  }
  visibleFlowPick.value = true;
};

// 关闭选择管理员弹框
const closeFlowPick = data => {
  const selectUserList = data.selectUserList[0] || { bizId: '', name: '' };
  form.value.managerUserId = selectUserList.bizId;
  form.value.managerUserIdWrapper = selectUserList.name;
};

const beforeUpload = file => {
  const isJpgOrPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/jpg' ||
    file.type === 'image/png' ||
    file.type === 'image/tif' ||
    file.type === 'image/jfif' ||
    file.type === 'image/webp' ||
    file.type === 'image/pjp' ||
    file.type === 'image/apng' ||
    file.type === 'image/pjpeg' ||
    file.type === 'image/avif' ||
    file.type === 'image/ico' ||
    file.type === 'image/tiff' ||
    file.type === 'image/bmp' ||
    file.type === 'image/xbm' ||
    file.type === 'image/jxl' ||
    file.type === 'image/svgz' ||
    file.type === 'image/gif' ||
    file.type === 'image/svg';
  if (!isJpgOrPng) {
    message.error('只能上传图片!');
    return Upload.LIST_IGNORE; //阻止列表展现
  }
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    message.error('图片大小不能超过5MB!');
  }
  return isJpgOrPng && isLt5M;
};

// 上传成功
const handleFileChange = (info, list) => {
  if (info.file.status === 'done') {
    // 设置临时fileList的值
    selectIconList.value = [info.file];
    // 将文件属性名和文件编码存入数组中
    message.success(`${info.file.name} 图片上传成功`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 图片上传失败`);
  }
};

//下载图片
const downloadPhoto = file => {
  let id = file.response ? file.response.data.fileId : file.uid;
  FileApi.download({ token: getToken(), fileId: id });
};

// 点击预览图片
const handlePreviewPhoto = async file => {
  previewImage.value = file.url || file.preview || file.thumbUrl;
  previewVisible.value = true;
};
</script>

<style scoped lang="less">
.flow-icon-item {
  width: 40px;
  height: 40px;
  margin: 6px;
  position: relative;
  cursor: pointer;

  &.active {
    opacity: 1;
    -webkit-filter: grayscale(100%);
    -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%);
    -o-filter: grayscale(100%);
    filter: grayscale(100%);
    filter: gray;
  }

  &:hover {
    opacity: 1;
  }
}

.type-icon {
  margin-bottom: 10px;
}
</style>
