<!--
 * @Author: sujunling
 * @Date: 2023-08-15 22:08:21
 * @LastEditors: sujunling
 * @LastEditTime: 2023-08-17 15:59:13
 * @FilePath: \xld-gis-admin\src\views\resource\map\SourceDetail.vue
 * @Description: 地图资源明细界面
-->
<template>
  <div class="source-detail">
    <a-form ref="formRef" :model="formState" :rules="rules" style="width: 100%">
      <div class="compontents">
        <div class="title">基本信息</div>
        <a-row class="form-container">
          <a-col :span="12" class="form-col">
            <a-form-item ref="servicename" label="组件名称" name="servicename" class="label-form-item">
              <a-input v-model:value="formState.servicename" placeholder="请输入组件名称" :disabled="isView" />
            </a-form-item>
          </a-col>

          <a-col :span="12" class="form-col">
            <a-form-item ref="servicealiasname" label="组件别名" name="servicealiasname" class="label-form-item">
              <a-input v-model:value="formState.servicealiasname" placeholder="请输入组件别名" :disabled="isView" />
            </a-form-item>
          </a-col>

          <a-col :span="24" class="form-col">
            <a-form-item ref="description" label="组件描述" name="description" class="label-form-item">
              <a-textarea placeholder="请输入组件描述" v-model:value="formState.description" :rows="2" :disabled="isView" />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="9" class="form-col">
            <a-form-item ref="servicetype" label="适合申请流程" name="servicetype" class="label-form-item">
              <a-select v-model:value="formState.servicetype">
                <template v-for="(tag, index) in assemblyType" :key="index">
                  <a-select-option :value="tag.value">{{ tag.value }}</a-select-option>
                </template>
              </a-select>
            </a-form-item>
          </a-col> -->
          <a-col :span="12" class="form-col">
            <!-- <a-form-item ref="servicetype" label="资源类型" name="servicetype" class="label-form-item">
              <a-select v-model:value="formState.servicetype">
                <template v-for="(tag, index) in assemblyType" :key="index">
                  <a-select-option :value="tag.value">{{ tag.value }}</a-select-option>
                </template>
              </a-select>
            </a-form-item> -->
            <a-form-item ref="servicetype" label="组件类型" name="servicetype" class="label-form-item">
              <a-select v-model:value="formState.servicetype" :disabled="isView" placeholder="请输入组件类型">
                <template v-for="tag in assemblyType" :key="tag.value">
                  <a-select-option :value="tag.value" :disabled="isView">{{ tag.label }}</a-select-option>
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12" class="form-col">
            <a-form-item ref="crs" label="组内顺序" name="crs" class="label-form-item">
              <a-input v-model:value="formState.crs" :rows="2" :disabled="isView" />
            </a-form-item>
          </a-col>
          <a-col :span="8" class="form-col">
            <a-form-item ref="thumbnail" label="缩略图" name="thumbnail" class="label-form-item">
              <a-upload :beforeUpload="beforeUploadImg" :remove="removeImg" :custom-request="customUpload"
                v-model:file-list="fileList" :disabled="isViewImg">
                <a-button style="background-color: #0671dd; color: #fff; border-radius: 4px" :disabled="isView">
                  <upload-outlined></upload-outlined>
                  文件上传
                </a-button>
              </a-upload>
              <span class="updateImg" @click="imgBut" v-if="!isView"></span>
            </a-form-item>
          </a-col>
          <a-col :span="16" class="form-col">
            <div class="wrapperImg" v-if="formState.mapingurl">
              <img v-if="formState.mapingurl" :id="formState.mapingurl" :src="getImg(formState.mapingurl)" alt="图片">
              <!-- <p v-else>无预览图</p> -->
            </div>
          </a-col>
        </a-row>
      </div>
    </a-form>
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  ref,
  toRefs,
  reactive,
  UnwrapRef,
  onMounted,
  watch,
} from 'vue';
import { BasicForm } from '/@/components/Form/index';
import { UploadOutlined } from '@ant-design/icons-vue';
import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface';
import { useMessage } from '/@/hooks/web/useMessage';
// 加载菜单数据
import Moment from 'moment';
import { insertService, updateService, update, getImgUrl } from '/@/api/dataAdmin/assembly';
import { session } from '/@/utils/Memory.js';
import { message } from 'ant-design-vue';

const props = {
  formData: { type: Object, default: ref(null) },
  isView: { type: Boolean, default: ref(false) },
  isUpdate: { type: Boolean, default: ref(false) },
};

interface FormState {
  source: '',
  servicetype: string,
  publiccurl: string;
  servicename: string;
  mapingurl: string,
  servicealiasname: string;
  description: string;
  publishtime: string;
  publisher: string;
  updateType: string;
  updatetime: string;
  public: boolean;
  share: boolean;
  searched: boolean;
  externalApply: boolean;
  date1: undefined;
  crs: 0
}
export default defineComponent({
  name: 'SourceDetail',
  components: { BasicForm, UploadOutlined },
  props,
  setup(props, { emit }) {
    const data = reactive({
      detail: props.formData,
      isUpdate: props.isUpdate,
      isView: props.isView,
      // fileList: [],
    });
    var fileList = ref([]);
    var isViewImg = ref(false);
    var assemblyType = ref([
      { value: '地图浏览工具', label: '地图浏览工具', },
      { value: '服务加载工具', label: '服务加载工具', },
      { value: 'GIS功能工具', label: 'GIS功能工具', },
      { value: '空间分析工具', label: '空间分析工具', },
      { value: '三维可视化效果工具', label: '三维可视化效果工具', },
    ])

    const formRef = ref();
    const formState: UnwrapRef<FormState> = reactive({
      mapingurl: '',
      servicename: '',
      publiccurl: '',
      servicealiasname: '',
      servicetype: undefined,
      description: '',
      publishtime: '',
      publisher: '',
      updateType: '',
      updatetime: '',
      public: true,
      share: true,
      searched: true,
      externalApply: true,
      date1: undefined,
      crs: 0
    });
    const moment = Moment;
    const rules = {
      // mapingurl: [{ required: true, message: '请输入服务地址', trigger: 'blur' }],
      servicetype: [{ required: true, message: '请选择资源类型', trigger: 'change' }],

      servicename: [
        { required: true, message: '请填写组件名称', trigger: 'blur' },
        { min: 1, max: 20, message: '长度必须在3到20个字符', trigger: 'blur' },
      ],
      servicealiasname: [
        { required: true, message: '请输入组件别名', trigger: 'blur' },
        { min: 1, max: 20, message: '长度必须在3到20个字符', trigger: 'blur' },
      ],
      systag: [{ required: true, message: '请选择系统标签', trigger: 'change' }],
      date1: [{ required: true, message: 'Please pick a date', trigger: 'change', type: 'object' }],
      type: [
        {
          type: 'array',
          required: true,
          message: 'Please select at least one activity type',
          trigger: 'change',
        },
      ],
      resource: [{ required: true, message: 'Please select activity resource', trigger: 'change' }],
      desc: [{ required: true, message: 'Please input activity form', trigger: 'blur' }],
    };
    const { createMessage } = useMessage();
    watch(
      () => props.formData,
      (obj) => {
        data.detail = obj;
        console.log('组件formData', obj);
        if (data.isUpdate) setFormData()
      }
    );
    watch(
      () => props.isUpdate,
      (obj) => {
        data.isUpdate = obj;
        if (!data.isUpdate) resetForm()
      }
    );
    watch(
      () => props.isView,
      (obj) => {
        data.isView = obj;
      }
    );
    const submitForm = () => {
      if (data.isView) {
        emit('closeModal');
        return
      }
      try {
        formRef.value
          .validate()
          .then(async () => {
            const params = setSubmitForm();
            if (params) {
              if (data.isUpdate) {
                params.servicebase.serviceid = data.detail.serviceid;
                params.servicebase.id = data.detail.id;
                if (!params.servicebase.mapingurl) params.servicebase.mapingurl = data.detail.mapingurl;
                params.metadata.serviceid = data.detail.serviceid;
                params.metadata.id = data.detail.id;
                if (!params.metadata.mapingurl) params.metadata.mapingurl = data.detail.mapingurl;
                const res = await updateService(params);
                if (res && res?.status !== '-1') {
                  createMessage.success('修改组件资源成功！');
                  fileList.value = [];
                  resetForm();
                  emit('RtnMain', true);
                } else createMessage.error('修改组件资源失败！,失败原因：' + res?.message, 1);
              } else {
                const res = await insertService(params);
                if (res && res?.status !== '-1') {
                  createMessage.success('新增组件资源成功！');
                  fileList.value = [];
                  resetForm();
                  emit('RtnMain', true);
                } else createMessage.error('新增组件资源失败！,失败原因：' + res?.message, 1);
              }
            }
          })
          .catch((error: ValidateErrorEntity<FormState>) => {
            createMessage.error('请完成必填信息！', 1);
            console.log('error', error);
          });
      } catch (ex) {
        console.log(ex);
      }
    };

    const resetForm = () => {
      formState.mapingurl = '';
      fileList.value = [];
      formRef.value.resetFields();
    };

    /**
     * 设置提交数据
     */
    const setSubmitForm = () => {
      const userinfo = session.getItem('userInfo');
      return {
        type: 'SR',
        servicebase: {
          publisher: userinfo?.EMPLOYEE?.NAME, //'系统管理员',
          username: userinfo?.EMPLOYEE?.NAME, //'系统管理员',
          userid: userinfo?.EMPLOYEE?.EMPLOYEE_ID, //'27AF004A-8BDN-885T-30FU-89DE3388762B',
          servicealiasname: formState.servicealiasname, //资源别名
          description: formState.description, //资源描述
          ispublic: formState.public ? '1' : '0', //是否公开
          searched: formState.searched ? '1' : '0', //是否展示
          externalApply: formState.externalApply ? '1' : '0', //外部申请
          servicename: formState.servicename, //资源名
          otherService: '',
          source: formState.servicetype, //资源类型
          mapingurl: formState.mapingurl, //服务地址
          publiccurl: formState.publiccurl, //数据表
          crs: formState.crs,//小组类顺序
        },
        metadata: {
          crs: formState.crs,//小组类顺序
          publiccurl: formState.publiccurl, //数据表
          source: formState.servicetype, //资源类型
          mapingurl: formState.mapingurl, //服务地址
          name: formState.servicename, //资源名
          servicealiasname: formState.servicealiasname, //资源别名
          thumbnail: '',
          description: formState.description,
          updateType: formState.updateType, //更新方式
          workSpace: '',
          ishistory: '0',
          shsqlc: 'ggdata',
          urlInfo: '',
          otherService: '',
          bz: '',
          ispublic: formState.public ? '1' : '0', //是否公开
          searched: formState.searched ? '1' : '0', //是否展示
          externalApply: formState.externalApply ? '1' : '0', //外部申请
          isShow: formState.share ? '1' : '0',
          publisher: userinfo?.EMPLOYEE?.NAME, //'系统管理员',
          username: userinfo?.EMPLOYEE?.NAME, //'系统管理员',
          userid: userinfo?.EMPLOYEE?.EMPLOYEE_ID, //'27AF004A-8BDN-885T-30FU-89DE3388762B',
        }
      };
    };
    /**
     * 设置表单数据
     */
    const setFormData = () => {
      formState.public = data.detail?.ispublic === '1' ? true : false;
      formState.servicename = data.detail?.servicename;
      formState.publiccurl = data.detail?.publiccurl;
      formState.servicetype = data.detail?.source;
      formState.crs = data.detail?.crs;
      formState.description = data.detail?.description;
      formState.mapingurl = data.detail?.mapingurl;
      formState.publishtime = data.detail?.publishdate
      formState.publishtime = data.detail?.publishdate ? moment(data.detail?.publishdate).format('YYYY-MM-DD HH:mm:ss') : '';
      formState.publisher = data.detail?.publisher;
      formState.servicealiasname = data.detail?.servicealiasname;
      formState.updatetime = data.detail?.updatedate ? moment(data.detail?.updatedate).format('YYYY-MM-DD HH:mm:ss') : '';
      formState.searched = data.detail?.searched === 0 ? false : true;
    };

    onMounted(() => {
      resetForm();
    });

    function beforeUploadImg() {
    }

    function removeImg() {
      formState.mapingurl = '';
    }

    function imgBut() {
      if (fileList.value.length) {
        return message.error('只能上传一个文件,请先删除之前的文件！')
      } else if (fileList.value.length == 0) {
        document.getElementById("thumbnail").click()
      }
    }

    function customUpload({ file, onSuccess, onError }) {
      const formData = new FormData();
      formData.append('file', file);
      update(formData, session.getItem('sysFild').dirId).then(r => {
        if (r && r.resp_code == 0 && r.resp_msg == "OK") {
          formState.mapingurl = `${r.datas.id},${r.datas.dirId}`;
          // isViewImg.value = true;
          onSuccess()
        } else {
          onError()
        }
      })
    }

    //获取图片
    function getImg(i) {
      if (i) {
        var arr = i.split(',')
        arr.length > 1 && getImgUrl(arr[0], arr[1]).then(r => {
          var d = document.getElementById(i);
          if (d) d.src = r;
        })
      }
    }
    return {
      imgBut,
      removeImg,
      beforeUploadImg,
      getImg,
      fileList,
      isViewImg,
      assemblyType,
      customUpload,
      ...toRefs(data),
      formRef,
      moment,
      rules,
      formState,
      submitForm,
      resetForm,
      createMessage,
      setSubmitForm,
      setFormData,
    };
  },
});
</script>
  
<style scoped lang="less">
.updateImg {
  top: 0px;
  display: inline-block;
  background-color: rgb(6, 113, 221);
  color: rgb(255, 255, 255);
  border-radius: 4px;
  width: 110px;
  height: 32px;
  position: absolute;
  opacity: 0;
  cursor: pointer;
  z-index: 2;
}

.wrapperImg {
  width: 200px;
  height: 200px;
  overflow: hidden;
  border: solid 1px #eee;
}

.wrapperImg img {
  width: 200px;
  height: 200px;
}

.source-detail {
  height: 100%;
  width: 100%;
  padding: 0 20px;

  .compontents {
    width: 100%;
    height: auto;

    .title {
      height: 19px;
      line-height: 18px;
      padding-left: 6px;
      margin-bottom: 20px;
      border-left: 3px solid #0671dd;
      font-family: Source Han Sans CN;
      font-size: 16px;
      font-weight: 350;
      letter-spacing: 0px;
    }

    .form-container {
      width: 100%;
      height: auto;

      .form-col {
        height: 100%;
      }

      .form-col-left {
        padding-right: 20px;
      }
    }
  }
}

.label-form-item {
  :deep(.ant-form-item-label) {
    width: 90px;
  }

  :deep(.ant-form-item-control) {
    width: calc(100% - 90px);
  }
}
</style>
  