<template>
 <div class="position-re">
   <small-big v-if="isPreviewDialogIsShow" v-model:is-small-img-show="isPreviewDialogIsShow" :src="baseUrl() + '/fileController/image?path='+currentImgFile[0].resUrl"/>
   <my-breadcrumb class="my-breadcrumb" :breadcrumb-arr="myBread"></my-breadcrumb>
   <div class="back" @click="$emit('changeOperation','',{})"><span class="fa fa-reply cur-po " >返回</span></div>
   <div class="my-detail-main">
      <div class="block">
       <div class="my-b-title">服务信息</div>
       <div class="form">
         <diy-el-form :span="12" :forms="formConfig" ref="formRef1" v-model:model-form="forms">
           <template #sltappend>

             <el-upload

               :multiple="false"
               :limit="1"
               v-model:file-list="currentImgFile"
               :before-upload="beforeUpload.bind({
             gs:['png','jpg','jpeg'],
             tip:'请上传争取的文件格式'
             })"
               :on-success="uploadSucccess"
               :action="baseUrl() + '/ptjkInterface/select_parameter_upload?appkey='+new UserInfo().GetUserKeyCode()"
               :data="{
                 TYPE:'1'
               }"
               :headers="{
                  'Systemtype': 'ebb42096345340359741dcb9c039f15c'
                }"
               with-credentials
               ref="upload"
               :show-file-list="true"

               class="my-el-upload"
             >

               <!--                <template v-for="file in fileList" >-->
               <!--                  <span :key="file.name">{{ file.name }}</span>-->
               <!--                </template>-->
             </el-upload>
             <el-button plain class="my-preview-btn" @click="previewImg">预览</el-button>
           </template>
         </diy-el-form>

       </div>
     </div>
     <div class="block">
       <div class="my-b-title">接口信息</div>
       <div class="form">
         <diy-el-form ref="formRef3" :span="12" :forms="interfaceManageDetailFormInterface" v-model:model-form="forms">

         </diy-el-form>

       </div>
     </div>
<!--     <div class="block">-->

<!--       <div class="my-b-title">入参信息</div>-->
<!--       <div class="my-search-div-and-input"><el-input v-model="rcKeyWord" class="search"/><el-button @click="addTd('rc')" :icon="Plus"  /></div>-->
<!--       <my-table-->
<!--         :filter-meothod="row => row.PARAM_NAME?.includes(rcKeyWord)"-->
<!--         border-->
<!--         :table-data="rcTableData"-->
<!--         :headers="interfaceManageDetailTableHeaderRc"-->
<!--         :is-height-equal-max-height="true"-->
<!--         :page-size="6"-->
<!--       >-->

<!--         <template #[item.prop]="{data}" v-for="item in interfaceManageDetailTableHeaderRc.filter(i => i.prop!=='operation')">-->
<!--           <template v-if="data.isEdit && operationType!=='detail'">-->

<!--             <el-select v-if="item.prop === 'PARAM_TYPE'"  v-model="data[item.prop]">-->
<!--               <el-option value="" label="请选择"></el-option>-->
<!--               <el-option value="1" label="字符型"></el-option>-->
<!--               <el-option value="2" label="数值型"></el-option>-->
<!--               <el-option value="3" label="日期型"></el-option>-->
<!--               <el-option value="4" label="日期时间型"></el-option>-->
<!--               <el-option value="6" label="逻辑型"></el-option>-->
<!--               <el-option value="9" label="双精度型"></el-option>-->
<!--               <el-option value="10" label="整型"></el-option>-->
<!--               <el-option value="11" label="浮点型"></el-option>-->
<!--             </el-select>-->

<!--             <el-input v-else v-model="data[item.prop]"/>-->
<!--           </template>-->
<!--           <span v-else-if="item.prop === 'PARAM_TYPE'">{{getDataType(data[item.prop]) || ''}}</span>-->
<!--           <span v-else>{{data[item.prop]}}</span>-->
<!--         </template>-->

<!--       </my-table>-->
<!--     </div>-->
<!--     <div class="block">-->
<!--       <div class="my-b-title">出参信息</div>-->
<!--       <div class="my-search-div-and-input"><el-input v-model="cnKeyWord" class="search"/><el-button  @click="addTd('cc')"  :icon="Plus"  /></div>-->
<!--       <my-table-->
<!--         :filter-meothod="row => row.PARAM_NAME?.includes(cnKeyWord)"-->
<!--         border-->
<!--         :table-data="ccTableData"-->
<!--         :headers="interfaceManageDetailTableHeaderCc"-->
<!--         :is-height-equal-max-height="true"-->
<!--         :page-size="6"-->
<!--       >-->
<!--         <template #[item.prop]="{data}" v-for="item in interfaceManageDetailTableHeaderCc.filter(i => i.prop!=='operation')">-->
<!--           <template v-if="data.isEdit && operationType!=='detail'">-->

<!--             <el-select v-if="item.prop === 'PARAM_TYPE'"  v-model="data[item.prop]">-->
<!--               <el-option value="" label="请选择"></el-option>-->
<!--               <el-option value="1" label="字符型"></el-option>-->
<!--               <el-option value="2" label="数值型"></el-option>-->
<!--               <el-option value="3" label="日期型"></el-option>-->
<!--               <el-option value="4" label="日期时间型"></el-option>-->
<!--               <el-option value="6" label="逻辑型"></el-option>-->
<!--               <el-option value="9" label="双精度型"></el-option>-->
<!--               <el-option value="10" label="整型"></el-option>-->
<!--               <el-option value="11" label="浮点型"></el-option>-->
<!--             </el-select>-->

<!--             <el-input v-else v-model="data[item.prop]"/>-->
<!--           </template>-->
<!--           <span v-else-if="item.prop === 'PARAM_TYPE'">{{getDataType(data[item.prop]) || ''}}</span>-->
<!--           <span v-else>{{data[item.prop]}}</span>-->
<!--         </template>-->
<!--       </my-table>-->
<!--     </div>-->
   </div>
   <div class="detail-operation-btn" v-if="operationType !== 'detail'">
     <el-button :icon="Select" @click="saveS">保存</el-button>
     <el-button :icon="Close" @click="$emit('changeOperation','',{})">关闭</el-button>
   </div>
 </div>
</template>

<script>
import MyBreadcrumb from "@/components/common/MyBreadcrumb.vue";
import {
  interfaceManageDetailFormInterface,
  interfaceManageDetailFormService,
  interfaceManageDetailFormTool, interfaceOrderDetailFormInterface
} from "@/data/all-forms";
import {onBeforeMount, ref} from "vue";
import DiyElForm from "@/components/common/DiyElForm.vue";
import {Close, Plus, Select} from "@element-plus/icons-vue";
import MyTable from "@/components/common/MyTable.vue";
import {interfaceManageDetailTableHeaderCc, interfaceManageDetailTableHeaderRc} from "@/data/all-table-header";
import {
  addOrEditInterfaceInfo,
  getInterfaceParamsInfo,
  getInterManageDetailInfo, getToolTypeOptions
} from "@/service/system-manage/interface-manage";
import {baseUrl} from "@/service/config";
import {elAlert, handleMes, showMessage} from "@/unit/element-ui/tip";
import {uuidv4} from "@/unit/code";
import {formatDateFun} from "@/unit/time";
import SmallBig from "@/components/SmallBig.vue";
import {decode, encode} from "js-base64";
import {UserInfo} from "@/unit/UserInfo";

export default {
  name: "InterfaceManageDetail",
  methods: {
    UserInfo,
    baseUrl() {
      return import.meta.env.VITE_BASE_API
    }
  },
  computed: {
    Close() {
      return Close
    },
    Select() {
      return Select
    },
    Plus() {
      return Plus
    }
  },
  props:{
    currentOpObj:{},
    operationType:{

    }

  },
  components: {SmallBig, MyTable, DiyElForm, MyBreadcrumb},
  setup(props,{emit}){
    const rcKeyWord = ref('')
    const toolFire = ref([])
    const formRef1 = ref(null)
    const formRef2 = ref(null)
    const formRef3 = ref(null)
    const isPreviewDialogIsShow = ref(false)
    const formConfig = ref({...interfaceManageDetailFormService()})
    function saveS(){
      const isVForm = [formRef1.value,formRef3.value].filter(i => Boolean(i))
      Promise.all(isVForm.map(i => i.refEl.validate(isValid => {
        Promise.resolve(isValid)
      }))).then(res => {
        let isNotAllValid = res.find(i2 => {
          console.log(!i2,'sa')
          return !i2
        }) !== undefined
        if (!isNotAllValid){
          if (forms.value['SHARE_TYPE']?.includes('SHARING_TOOLKIT') && !(toolFire.value.length > 0)){
           elAlert('请上传工具包文件')
          }else {
            addOrEditInterfaceInfo({
              UUID:props.currentOpObj.UUID,
              TYPE:forms.value.TYPE,
              TEXT_ADDRESS:forms.value.TEXT_ADDRESS,
              RESOURCE_NAME:forms.value.RESOURCE_NAME,
              RESOURCE_TYPE:forms.value.RESOURCE_TYPE,
              // SHARING_TOOLKIT:forms.value.SHARE_TYPE.includes('SHARING_TOOLKIT')?'2':'1',
              // SHARING_INTERFACE:forms.value.SHARE_TYPE.includes('SHARING_INTERFACE')?'2':'1',
              RELEASE_TIME:forms.value.RELEASE_TIME,
              RELEASE_REMARKS:forms.value.RELEASE_REMARKS,
              RESOURCE_THUMBNAIL:(currentImgFile.value[0] && currentImgFile.value[0].resUrl) || '',

              // TOOLKIT_FILES:(toolFire.value[0] && toolFire.value[0].resUrl) || '',
              // TOOLKIT_REMARKS:forms.value.TOOLKIT_REMARKS ,
              INTERFACE_ADDRESS:forms.value.INTERFACE_ADDRESS ,
              INTERFACE_TYPE:forms.value.INTERFACE_TYPE ,
              REQUEST_MODE:forms.value.REQUEST_MODE ,
              INTERFACE_REMARKS:forms.value.INTERFACE_REMARKS ,
              USER_CODE:props.currentOpObj.USER_CODE,
              UNIT_CODE:props.currentOpObj.UNIT_CODE,
              // IN_PARAMETER:JSON.stringify(forms.value.IN_PARAMETER),
              IN_PARAMETER:forms.value.IN_PARAMETER?encode(forms.value.IN_PARAMETER):'',
              OUT_PARAMETER:forms.value.OUT_PARAMETER?encode(forms.value.OUT_PARAMETER):'',
              // OUT_PARAMETER:JSON.stringify(forms.value.OUT_PARAMETER),

            }).then(res => {
              handleMes(res,() => {
               emit('changeOperation','')
              })
            })
          }

        }
        console.log('assaasa',isNotAllValid,'isNotAllValid',res,typeof res[0])
      })

    }
    function previewImg(value) {
      if (!(currentImgFile.value.length > 0)){
        elAlert('请先上传文件')
      }else {
        isPreviewDialogIsShow.value = true
      }

    }

    function addTd(type) {
      let paramsObj = {
        'rc':{
          header:interfaceManageDetailTableHeaderRc,
          table:rcTableData.value
        },
        'cc':{
          header:interfaceManageDetailTableHeaderCc,
          table:ccTableData.value
        }
      }
      let obj = {}
      paramsObj[type].header.filter(i => i.prop!=='operation').forEach(i => {
        obj[i.prop] = ''
        obj.isEdit = true
      })
      obj.TYPE = type === 'rc'?'1':'2'
      obj.UUID = uuidv4()
      paramsObj[type].table.push(obj)

    }
    const rcTableData = ref([])
    const ccTableData = ref([])
     const cnKeyWord = ref('')

    function uploadSucccess(res,file) {

      console.log(res,file,'file')
      if (res.msg[0].success){
        currentImgFile.value = [].concat({
          ...file,
          resUrl:res.msg[0].error
        })
        // currentImgFile.value.resUrl = res.msg[0].error
        showMessage({
          type:'success',
          message:'上传成功'
        })
      }else {
        showMessage({
          type:'success',
          message:'上传失败'
        })
      }
    }
    function uploadSucccessTool(res,file) {

      console.log(res,file,'file')
      if (res.msg[0].success){
        toolFire.value = [].concat({
          ...file,
          resUrl:res.msg[0].error
        })
        // currentImgFile.value.resUrl = res.msg[0].error
        showMessage({
          type:'success',
          message:'上传成功'
        })
      }else {
        showMessage({
          type:'success',
          message:'上传失败'
        })
      }
    }
    function beforeUpload(file) {
      let neeReg = new RegExp(`\.(${this.gs.join('|')})$`)
      console.log(neeReg)
      if (!neeReg.test(file.name)){
        showMessage({
          type:'error',
          message:this.tip
        })
        return false
      }
      console.log(this,file,'beforeUpload')
      return true

    }
    const forms = ref({})
    const currentImgFile = ref([])
    function getDataType(num){
      let obj = {
        1:'字符型',
        2:'数值型',
        3:'日期型',
        4:'日期时间型',
        6:'逻辑型',
        9:'双精度型',
        10:'整形',
        11:'浮点型',
      }
      return obj[num]
    }
    const myBread = [
      {name:'接口管理'},
      {name:'配置'},
    ]
    onBeforeMount(() => {
      getToolTypeOptions().then(res => {
        const findToolType = formConfig.value.formItemsArr.find(i => i.modelValue === 'TYPE')
        findToolType.options = [{value:'',label:'请选择'}].concat(res.msg[0].Rows.map(i => {
          return {
            label:i.NAME,
            value:i.CODE,
          }
        }))
      })
      const shareT = []
      if (props.operationType !=='add'){
        getInterManageDetailInfo(props.currentOpObj.UUID).then(res => {
          if (res.msg[0].Rows[0].SHARING_INTERFACE === '2'){
           shareT.push('SHARING_INTERFACE')
          }
          if (res.msg[0].Rows[0].SHARING_TOOLKIT === '2'){
            shareT.push('SHARING_TOOLKIT')
          }
          if (res.msg[0].Rows[0].RESOURCE_THUMBNAIL){
            currentImgFile.value = [].concat( {
              name:res.msg[0].Rows[0].RESOURCE_THUMBNAIL.slice(res.msg[0].Rows[0].RESOURCE_THUMBNAIL.lastIndexOf('/') + 1),
              resUrl:res.msg[0].Rows[0].RESOURCE_THUMBNAIL,
            })

          }
          if (res.msg[0].Rows[0].TOOLKIT_FILES){
            toolFire.value = [].concat( {
              name:res.msg[0].Rows[0].TOOLKIT_FILES.slice(res.msg[0].Rows[0].TOOLKIT_FILES.lastIndexOf('/') + 1),
              resUrl:res.msg[0].Rows[0].TOOLKIT_FILES,
            })

          }

          forms.value = {
            ...forms.value,
            ...res.msg[0].Rows[0],
           SHARE_TYPE:shareT,
            RELEASE_TIME:res.msg[0].Rows[0].RELEASE_TIME?formatDateFun(+new Date(res.msg[0].Rows[0].RELEASE_TIME),'yyyy-MM-dd hh:mm:ss'):'',
            IN_PARAMETER:res.msg[0].Rows[0].IN_PARAMETER?decode(res.msg[0].Rows[0].IN_PARAMETER):'',
            OUT_PARAMETER:res.msg[0].Rows[0].OUT_PARAMETER?decode(res.msg[0].Rows[0].OUT_PARAMETER):'',

           // OUT_PARAMETER:JSON.parse(res.msg[0].Rows[0].OUT_PARAMETER),
          }
        })
        getInterfaceParamsInfo(props.currentOpObj.UUID).then(res => {
          rcTableData.value = res.msg[0].Rows.filter(i => +i.TYPE === 1)
          ccTableData.value = res.msg[0].Rows.filter(i => +i.TYPE === 2)
        })
      }
    })
    return {
      myBread,
      interfaceManageDetailFormService,
      interfaceManageDetailFormTool,
      forms,
      currentImgFile,
      previewImg,
      interfaceManageDetailFormInterface,
      cnKeyWord,
      rcTableData,
      interfaceManageDetailTableHeaderCc,
      interfaceManageDetailTableHeaderRc,
      ccTableData,
      addTd,
      getDataType,
      beforeUpload,
      uploadSucccess,
      saveS,
      formConfig,
      isPreviewDialogIsShow,
      toolFire,
      uploadSucccessTool,
      formRef1,
      formRef2,
      formRef3,
      rcKeyWord

    }
  }
}
</script>

<style scoped lang="scss">
.form{
  padding-right: 15%;
}
.my-el-upload{
  &.no-file{
    :deep{
      .el-upload-list{
        display: none;
      }
    }
  }
  :deep{
    .el-upload--text{
      display: block !important;
    }
  }
  height: unset;
}
.my-el-upload{

  :deep{
    .el-upload-list{
      margin-top: 8px;
      width: calc(100% - 60px);
      position: absolute;
      transform: translateY(-100%);
    }

  }
}
</style>
