<template>
    <div>
    <div class="app-container" style="margin-bottom: 12px;padding-bottom: 5px;border-radius: 10px;">
      <el-form ref="queryRef" :model="queryParams" :inline="true">
       

        <el-form-item label="图片类型">
          <el-select v-model="queryParams.type" placeholder="请选择协议类型" clearable style="width: 200px">
            <el-option :key="1" label="logo" :value="1" />
            <el-option :key="2" label="轮播图" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px">
            <el-option :key="1" label="可用" :value="1" />
            <el-option :key="2" label="不可用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="search">搜索</el-button>
          <el-button icon="Refresh" plain @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="app-container" style="margin-bottom: 20px;border-radius: 10px;">
      <el-button 
        type="primary" 
        plain 
        icon="Plus" 
        @click="showpop(1)"
      >新增</el-button>
      <el-table
        :data="dictlist"
        style="width: 100%;margin-top: 10px;"
        border
        stripe
        highlight-current-row
        row-key="id"
        max-height="600px"
      >

        <el-table-column min-width="100" label="图片类型" align="center" prop="type">
            <template #default="scope">
            <div>{{ scope.row.type == 1?'logo':'轮播图'}}</div>
            </template>
        </el-table-column>
        <el-table-column min-width="60" label="图片" align="center" prop="picUrl">
          <template #default="scope">
            <img :src="scope.row.picUrl" style="width: 50px;height: 50px;" />
          </template>
        </el-table-column>
        <el-table-column min-width="150" label="链接" align="center" prop="outLinks" />
        <el-table-column min-width="150" label="状态" align="center" prop="type">
            <template #default="scope">
            <div>{{ scope.row.status == 1?'可用':'不可用'}}</div>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="showpop(2,scope.row)">修改</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
        </el-table-column>
        <!-- <el-table-column label="创建时间" align="center" width="160" prop="createTime">
        <template #default="scope">
            <span>{{ dayjs(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}</span>
        </template>
        </el-table-column> -->
      </el-table>
      <!-- <div v-if="total > 10" style="display: flex;justify-content: right;padding-top: 20px;">
        <el-pagination
          v-model:current-page="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          background
          size="small"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="querytype"
        />
      </div> -->
      
    </div>
      <!--:row-style="{background: '#cde0f3'}"-->
      
      <!--添加字典类型-->
      <el-dialog 
        v-model="popshow" 
        :title="poptit" 
        width="500px" 
        append-to-body
        align-center
        :close-on-click-modal="false"
      >
        <el-form ref="typeform" :model="addObj" :rules="rules" label-width="100px">
            <el-form-item label="小程序" prop="appid">
            <el-select v-model="addObj.appid" placeholder="请选择协议类型" style="width: 100%">
                <el-option v-for="(n,i) in yxtype" :key="i" :label="n.dictName" :value="n.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="图片类型" prop="type">
            <el-select v-model="addObj.type" placeholder="请选择图片类型" style="width: 100%">
                <el-option :key="1" label="logo" value="1" />
                <el-option :key="2" label="轮播图" value="2" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="图片" prop="picUrl">
            <el-upload
              :headers="{
                Authorization:Token
              }"
              :data="{useFor:1}"
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleSuc"
              :before-upload="beforeAvatarUpload"
            >
            <img v-if="addObj.picUrl" :src="addObj.picUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <!-- <el-input v-model="addObj.picUrl" placeholder="请选择图片" /> -->
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="addObj.name" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="addObj.sort" placeholder="请输入排序" />
          </el-form-item>
          <el-form-item label="链接" prop="outLinks">
            <el-input v-model="addObj.outLinks" placeholder="请输入链接" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="addObj.status" placeholder="请选择协议类型" style="width: 100%">
                <el-option :key="1" label="可用" value="1" />
                <el-option :key="2" label="不可用" value="0" />
            </el-select>
        </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="save">确 定</el-button>
            <el-button @click="canceltype">取 消</el-button>
          </div>
        </template>
      </el-dialog>
  
    </div>
  </template>
  
  <script lang="ts" setup>
    import { 
      getdicttype,
      adddicttype,
      update,
      deltype
    } from '@/api/systemSet/xcximg'
    import { ref,reactive} from 'vue'
    import { ElMessage, ElMessageBox } from 'element-plus'
    import { showLoading,hideLoading } from '@/utils/loading'
    import { getdict } from '@/api/systemSet/dict'

    import type { UploadProps } from 'element-plus'
    import { getToken } from "@/utils/auth";

    const Token = `Bearer ${getToken()}`
    
    const uploadUrl = `${import.meta.env.VITE_APP_BASE_API}/resource/file/img/upload`
    //图片上传限制
    const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
        if (rawFile.type !== 'image/jpeg') {
          ElMessage.error('请上传jpg图片')
          return false
        } else if (rawFile.size / 1024 / 1024 > 2) {
          ElMessage.error('上传图片大小不能超过2MB')
          return false
        }
        return true
      }

    //图片上传成功回调
    const handleSuc: UploadProps['onSuccess'] = (
      response,
      uploadFile
    ) => {
      if(response.code == 1000){
        addObj.picUrl = response.data
      }
      //addObj.picUrl = URL.createObjectURL(uploadFile.raw!)
      console.log(uploadFile)
    } 
    let yxtype = ref<any>([])
      getdict({
        typeCode:'wxxcx'
      }).then(rps => {
        yxtype.value = rps.data
      })  

    //查询        
    let queryParams = reactive({
        appid:'',	
        type:'',	      //类型：1-logo，2-轮播图
        status:''     	//状态：1-可用，0-不可用
     })
  
     let dictlist = ref<any>([])
     function querytype() {
      dictlist.value.splice(0)
      getdicttype(queryParams).then(rps => {
        dictlist.value = rps.data
      })
     }
  
     let queryRef = ref()
     function resetQuery() {
      queryRef.value?.resetFields()
     }
  
     function search() {
      querytype()
     } 
    
     function handleSizeChange(val:number) {
        querytype()
     }
  
     //新增、修改
     let cztype = ref(1)
     let typeform = ref()
     let popshow = ref(false) 
     let poptit = ref('添加协议')
     let addObj = reactive({
        appid:'',
        type:'',	    //类型：1-logo，2-轮播图
        status:'1',   //状态：1-可用，0-不可用
        pkId:'',
        name:'',	    //名称
        picUrl:'',    //图片地址
        sort:'',	    //排序	
        linkFlag:'',	//链接标识
        outLinks:''	  //外链地址
      })
      const rules = {
        appid: [
            { required: true, message: "请选择小程序", trigger: "blur" },
        ],
        type: [
            { required: true, message: "请选择图片类型", trigger: "blur" },
        ],
        picUrl:[
            { required: true, message: "请上传图片", trigger: "blur" },
        ]
      }

      function caoztype(obj:any) {
        if(cztype.value == 1){
          return adddicttype(obj) 
        }
        return update(obj)
      }
  
      function showpop(type:number,row?:any) {
        cztype.value = type
        popshow.value = true
        poptit.value = type == 1?'添加图片':'修改图片'
        typeform.value?.resetFields()
        if(row){
          addObj.pkId = row.pkId
          addObj.appid = row.appid
          addObj.type = row.type+''
           
          addObj.status = row.status +''   
          addObj.name = row.name	    
          addObj.picUrl = row.picUrl    
          addObj.sort = row.sort	    	
          addObj.linkFlag = row.linkFlag	
          addObj.outLinks = row.outLinks	  
        }else{
          addObj.pkId = ''
          addObj.appid = ''
          addObj.type = ''     
          addObj.status = '1' 
          addObj.name = ''	    
          addObj.picUrl = ''    
          addObj.sort = ''	    	
          addObj.linkFlag = ''	
          addObj.outLinks = ''	 
        }
      }
      
      //保存
      function save() {
        typeform.value?.validate((valid:Boolean) => {
          if (valid) {
            showLoading()
            caoztype(addObj).then(() => {
              hideLoading()
              ElMessage({
                type: 'success',
                message: cztype.value == 1?'添加成功':'修改成功'
              })
              setTimeout(() => {
                popshow.value = false
                search()
              },1000)
            }).catch(() => {
                hideLoading()
            })
          }
        })
      }
  
      //删除
      function handleDelete(row:any) {
        ElMessageBox.confirm(
        `确定删除图片?`,
        '温馨提示',
        {
          // confirmButtonText: '',
          // cancelButtonText: 'Cancel',
          type: 'warning',
        }
      ).then(() => {
        deltype(row.pkId).then(rps => {
            ElMessage({
              type: 'success',
              message: '删除成功'
            })
            querytype()
          })
        })
      }
  
      function canceltype() {
        popshow.value = false
      }

     querytype()
  </script>
  <style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>
  
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  </style>