<template>
  <div class="page-box">
    <moduleView :propConfig="config" ref="view" v-loading="load" @pagination="pagination" @onRefresh="getList" @resert="queryList" @search="queryList" @clickHandle="clickHandle" @modalHandle="modalHandle" @detail="detail" />
    <el-drawer
      size="50%"
      v-model="drawer"
      close-on-click-modal
      title="操作日志"
      direction="rtl"
    >
      <el-table ref="operlogRef" :data="logData">
        <el-table-column label="日志编号" align="center" prop="operId" width="130" />
        <el-table-column label="操作类型" align="center" prop="businessType">
          <template #default="scope">
              <dict-tag :options="sys_oper_type" :value="scope.row.businessType" />
          </template>
        </el-table-column>
        <el-table-column label="操作人员" align="center" width="110" prop="operName" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']" />
        <el-table-column label="主机" align="center" prop="operIp" width="130" :show-overflow-tooltip="true" />
        <el-table-column label="操作状态" align="center" prop="status">
          <template #default="scope">
              <dict-tag :options="sys_common_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作日期" align="center" prop="operTime" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
          <template #default="scope">
              <span>{{ parseTime(scope.row.operTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-log">
        <el-pagination layout="prev, pager, next" :total="logPage.total" @current-change="handleCurrentChange"
        :current-page="logPage.pageNo" />
      </div>
    </el-drawer>
  </div>
</template> 

<script setup>
  import { computed,getCurrentInstance,ref, shallowRef  } from "vue";
  const { proxy } = getCurrentInstance();
  import {appList,addApp,updateApp,deleApp,disableApp,enableApp} from '@/api/base/shopManage'
  const { sys_oper_type, sys_common_status } = proxy.useDict("sys_oper_type","sys_common_status");
  import { list} from "@/api/monitor/operlog";
  import txt from "./txt.vue";
  // import merchant from "./merchant.vue";
  import stateRadio from "@/components/stateRadio/stateRadio.vue";
  const drawer = ref(false)
  const config = ref({
    attr:{
      calculateH:true
    },
    search:{
      attr:{
        size:'mini'
      },
      columns:[
        [{
          span:8,
          // label:'设备名称',
          labelWidth:1,
          prop:'searchText',
          component:'by-input',
          compConfig:{ 
            attr:{
              placeholder:'请输入小程序名称、应用ID、所属商户',
              prefixIcon:'vxe-icon-search'
            }
          }
        }]
      ]
    },
    tool:{
      tools:{
        // export:true,
        add:true,
        search:true,
        refresh:true
      },
      customTools:[{
        name: '导出', 
        icon: 'bottom',
        event:{
          click:() =>{
            loadDown()
          }
        }
      }, {
        name: '操作日志', 
        icon: 'Notebook',
        event:{
          click:() =>{
            drawer.value = true
          }
        }
      }]
    },
    table:{
      attr:{
        size:'mini',
        seq:true,
        align:'center',
        // checkbox:true
      },
      columns:[
      {
        isDetail:true,
        title:'小程序名称',
        field:'appName',
      },  
      {
        title:'应用ID',
        field:'appkey',
      },
      {
        title:'所属商户',
        field:'commercialName'
      },
      {
        title:'状态',
        field:'state',
        component: 'textChange',
        compConfig:{
          attr:{
            data:[{
              label:'已启用',
              value:1,
              backgroundColor:'#f0f9eb',
              color:'#67c23a'
            },{
              label:'已禁用',
              value:0,
              backgroundColor:'#fef0f0',
              color:'#f56c6c'
            }]
          }
        }
      },
      {
        title:'创建时间',
        field:'createTime'
      },
      {
        title:'操作',
        action:true,
        plugins:[{
          name:'禁用',
          event:{
            show:row => {
              return row.state == 1
            },
            click:item => {
             disableHandle(item)
            }
          }
        },{
          name:'启用',
          event:{
            show:row => {
              return row.state == 0
            },
            click:item => {
              enableHandle(item)
            }
          }
        }]
      }]
    },
    modal:{
      tool:{
        tools:{
          return:true,
          add:true
        }
      },
      form:{
        attr:{
          width:'1000px',
          size:'small',
          labelWidth:'130px',
          rules:{
            appLogo:[
              {required: true, message: '请上传小程序logo', trigger: 'change'}
            ],
            appName:[
              {required: true, message: '请输入小程序名称', trigger: 'blur'}
            ],
            appIntroduce:[
              {required: true, message: '请输入小程序描述', trigger: 'blur'},
            ],
            commercialName:[
              {required: true, message: '请选择商户', trigger: 'change'}
            ],
            callBack:[
              {required: true, message: '请输入回调地址', trigger: 'blur'}
            ]
          }
        },
        columns:[
          [{
            label:'小程序logo',
            prop:'appLogo',
            component:'ByUpload'
          }],
          [{
            label:'小程序名称',
            prop:'appName',
            component:'by-input'
          }],
          [{
            label:'小程序描述',
            prop:'appIntroduce',
            component:'by-input',
            compConfig:{
              attr:{
                type:'textarea'
              }
            }
          }],
          [{
            label:'商户',
            prop:'commercialName',
            component:'by-select',
            compConfig:{
              attr:{
                label:'commercialName',
                value:'commercialId',
                retConfig:{
                  commercialName:'commercialName',
                  commercialId:'commercialId'
                },
                // disabledHandle: item => {
                //   return item.state == 1 ? false : true
                // }
              },
              request:{
                url:'/app/getCommercialList',
                method:'get'
              }
            }
          }],
          [{
            label:'回调地址',
            prop:'callBack',
            component:'by-input',
            compConfig:{
              attr:{
                type:'textarea'
              }
            }
          }],
          [{
            label:'状态',
            prop:'state',
            component:shallowRef(stateRadio)
          }],
          [{
            label:'应用ID',
            prop:'appkey',
            component:shallowRef(txt)
          }],
          [{
            label:'应用秘钥',
            prop:'appSecret',
            component:shallowRef(txt)
          }],
          [{
            label:'备注',
            prop:'annotation',
            component:'by-input',
            compConfig:{
              attr:{
                type:'textarea'
              }
            }
          }]
        ]
      }
    }
  })
  const logData = ref([])
  const logPage = ref({
    pageNo: 1, //当前页
    pageSize: 20, //每页条数
    total: 0 //总条数
  })

  const load = ref(false)
  const isSearch = ref(false)
  const timeNum = ref(0);
  const initLog= () => {
    list({
      pageNum:logPage.value.pageNo,
      pageSize:logPage.value.pageSize,
      title:'小程序'
    }).then(res => {
      logData.value = res.rows;
      logPage.value.total = res.total;

    }).catch(()=> {

    })
  }

  //导出
  const loadDown = () => {
    let data = proxy.$refs.view.getQuery();
    data.pageNum = data.pageNo;
    delete data.pageNo;
    proxy.download('/app/export',data,`小程序_${new Date().getTime()}.xlsx`)
  }

  const handleCurrentChange = v => {
    logPage.value.pageNo = v;
    initLog()
  }
  // 禁用
  const disableHandle = item => {
    disableApp(item.appkey).then(() => {
      proxy.$message({
        message: '“' + item.appName + '”' + '已成功禁用！',
        type: 'success'
      })
      getList()
      initLog()
    }).catch(() => {})
  }
  //启用
  const enableHandle = item => {
    enableApp(item.appkey).then(() => {
      proxy.$message({
        message:  '“' + item.appName + '”' + '已成功启用！',
        type: 'success'
      })
      getList()
      initLog()
    }).catch(() => {})
  }

  const detail = () => {
    config.value.modal.tool.tools.save = true;
    delete config.value.modal.tool.tools.add;
    proxy.$refs.view.initFormTool();
  }

  const clickHandle = n => {
    if(n == 'onAdd'){
      config.value.modal.tool.tools.add = true;
      delete config.value.modal.tool.tools.save;
      proxy.$refs.view.initFormTool();
    }
    if(n == 'onDelete'){
      delHandle()
    }
  }
  const modalHandle = n =>{
    if(n == 'onAdd'){
      proxy.$refs.view.getFormValidate(addData)
    }

    if(n == 'onSave'){
      proxy.$refs.view.getFormValidate(onSave)
    }
  }
  const delHandle = () => {
    let data = proxy.$refs.view.getSelectData();
    let ids = []
    if(!data && data.lenght == 0) {
      proxy.$message('请选择数据')
      return
    }
    for(const item of data) {
      ids.push(item.equipmentId)
    }
    proxy.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      load.value = true;
      deleApp({
        appKeys:appkey,
      }).then(()=>{
        proxy.$message({message:'删除成功！',type:'success'})
        load.value = false;
        getList();
      }).catch(()=>{
        load.value = false;
      })
    }).catch(()=>{})
  }
  //添加
  const addData = () => {
    let value = proxy.$refs.view.getFormValue();
    if(value){
      load.value = true;
      addApp(value).then(res =>{
        load.value = false;
        proxy.$message({
          message:res.msg,
          type:'success'
        });
        proxy.$refs.view.closeModal();
        getList();
      }).catch(()=>{
        load.value = false;
      })
    }
  }
  //保存
  const onSave = () => {
    let data = proxy.$refs.view.getFormValue();
    load.value = true;
    updateApp(data).then(res => {
      proxy.$message({
        message:res.msg,
        type:'success'
      });
      load.value = false;
      proxy.$refs.view.closeModal();
      pagination();
    }).catch(() => {
      load.value = false;
    })
  }
  const pagination = () => {
    if(isSearch.value){
      queryList();
    }else{
      getList()
    }
  }
  //列表请求（包含分页和搜素条件）
  const queryList = () => {
    isSearch.value = true;
    let data = proxy.$refs.view.getQuery();
    requestList(data);
  }
  const getList = () => {
    if(!proxy.$refs.view){
      if(timeNum.value > 5){
        return
      }
      setTimeout(()=>{
        getList()
      },500) 
      timeNum.value ++;
      return
    }
    timeNum.value = 0;
    isSearch.value = false;
    let data = proxy.$refs.view.getPage();
    requestList(data);
  }
  const requestList = data => {
    load.value = true;
    data.pageNum = data.pageNo;
    delete data.pageNo;
    appList(data).then(res => {
      load.value = false;
      proxy.$refs.view.setTableValue(res.data.records);
      let page = {
        pageNo: res.data.current, //当前页
        pageSize: data.pageSize, //每页条数
        total: res.data.total //总条数
      };
      proxy.$refs.view.setPage(page)

    }).catch(()=>{
      load.value = false;
    })
  }
  nextTick(()=>{
    getList()
  })
  const calculateTable = () => {
    nextTick(() => {
      proxy.$refs.view.initTable()
    })
  }
  defineExpose({
    calculateTable
  })

  initLog()
</script>

<style scoped>
.page-log{
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
</style>
