<template>
  <div>
    <crud-template ref="crudRef" class="as-weight" :submit-state="false" :home-data="field" :tableData="tableData"
                   @btnSearch="btnSearch" @CurrentChange="handleCurrentChange" @importData="importData" @download="downloadHandle"
                   @refreshLeft="refreshLeft" @add="Adds" @cancel="cancel" @submit="submitAdd" @handleEdit="handleEdit" @handleDelete="deleteHandle">
      <template #search>
        <el-input maxlength="60" v-trim clearable v-model="searchForm.version" style="width: 200px"
                  placeholder="请输入版本号" />
        <el-select clearable v-model="searchForm.status" style="width: 200px;" placeholder="状态">
          <el-option v-for="item in ENABLE_STATUS" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-date-picker unlink-panels v-model="value1" type="daterange" range-separator="到" start-placeholder="发布日期始"
                        end-placeholder="发布日期止" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="dateChangeHandle" style="width: 250px"/>
      </template>

      <!-- 状态 -->
      <template #status="item">
        <el-switch :disabled="!IsPermission(route, 'STAET_LIST')"
                   :model-value="item.scope.row.status === 'ENABLE' || item.scope.row.status === '启用'"
                   active-color="#13ce66" inactive-color="#ff4949"
                   @change="(value) => handleBeforeChange(value, item.scope.row.id, item.scope.row)">
        </el-switch>
      </template>

    </crud-template>
  </div>
</template>
<script setup lang="ts">
import {ref, onMounted, watch, nextTick, toRaw, computed} from 'vue'
import CrudTemplate from '@/crud/index.vue'
import BaseService from '@/utils/baseService' //引入接口请求
import {
  ElMessage,
} from 'element-plus' //提示
import { useRoute } from 'vue-router'
import { IsPermission } from '@/router/routerUtil'
import $storeinitData from "@/store/initData";
//或取路由传入过来的对象数据
const route = useRoute()
const crudRef = ref()
const value1 = ref()
let tableData: any = ref([])
const itemStartValue = ref(1)
//查询参数
const searchForm = ref({})
let formLabelWidth = '150px';
const ENABLE_STATUS = computed(() => {
  return $storeinitData.state.dictData['ENABLE_DISABLE_STATUS'] || []
})
const field = ref({
  tabSize: "small", //Table 的尺寸 large / default /small (默认default)
  searchShow: IsPermission(route, 'QUERY_BASE'), //是否显示搜索模块(默认false) IsPermission(route, 'QUERY_BASE')
  border: true, //是否添加边框(默认false)
  dialogCustom: false, //自定义Dialog (默认false)
  dialogFooter: false, //隐藏弹窗页脚显示 (默认false)
  dialogWidth: "40%", //dialog宽度 (默认40%)
  dialogInfoWidth: "60%",
  crudShow: true, //是否显示CURD操作栏 (默认true)
  crudChildShow: true, //是否显示CURD子操作栏 (默认true)
  paginStart: true, //是否显示分页查询 (默认false)
  dataListLoading: false,
  paging: {
    pageSize: 10,
    currentPage: 1,
    total: 0
  },
  crud: {
    add: IsPermission(route, 'ADD_BASE'),
    edit: false,
    delete: false,
    derive: false,
    search: false,
    refresh: false,
  },
  searchOperation: {
    isDownload: false,
    isAdd: false,
    isTransferMachine: false,
  },
  tableSize: -1,
  operateShow: true, //是否为表格添加操作栏(默认true)
  operateTitle: "操作", //操作栏标题(默认为"")
  operateFixed: true, //操作栏是否固定(默认false)
  operateWidth: "200", //操作栏宽度
  operate: {
    info: IsPermission(route, 'INFO_LIST'), //是否编辑(默认true) IsPermission(route, 'INFO_LIST')
    edit: IsPermission(route, 'EDIT_LIST'), //是否编辑(默认true) IsPermission(route, 'EDIT_LIST')
    delete: IsPermission(route, 'DEL_LIST'), //是否删除(默认true) IsPermission(route, 'DEL_LIST')
    announcement: false, // 公告
    remark: false, // 详情
    forbidden: false, // 禁用
    enable: false, // 启用
    authorization: false, // 授权
    cancel: false, // 取消订单
    writeOff: false, // 注销
    make: false, // 补缴
  },
  extend: [
    {
      label: "序号",
      type: "index", //类型:selection,index,expand
      width: "50", //表头宽度
    },
  ],
  field: [
    {
      prop: "version",
      label: "版本号",
      width: "100",
      form: {
        hideEdit: false,
        formLabelWidth: formLabelWidth,
        type: 'input',
        required: true,
      }
    },
    {
      prop: "publisher",
      label: "发布人",
      form: {
        hideEdit: true,
        width: '90%',
        formLabelWidth: formLabelWidth,
        type: 'input',
      }
    },
    {
      prop: "releaseTime",
      label: "发布时间",
      width: "140",
      form: {
        hideEdit: true,
        width: '90%',
        formLabelWidth: formLabelWidth,
        type: 'input',
      }
    },
    {
      prop: "url",
      label: "下载地址",
      form: {
        required: true,
        width: '90%',
        formLabelWidth: formLabelWidth,
        type: 'upload',
        accept: '.apk',
        placeholder: '请上传APP安装包',
      }
    },
    {
      prop: "status",
      label: "状态",
      slotSet: true,
      slotSetName: 'status',
      // form: {
      //   formLabelWidth: formLabelWidth,
      //   type: 'select',
      //   hideEdit: false,
      //   width: '90%',
      //   listData: ENABLE_STATUS,
      // }
    },
    {
      prop: "isUpLevel",
      label: "是否强制更新",
      width: "80",
      form: {
        formLabelWidth: formLabelWidth,
        type: 'select',
        required: true,
        listData: [
          {
            label: '否',
            value: '0',
          },
          {
            label: '是',
            value: '1',
          },
        ],
      }
    },
    {
      prop: "message",
      label: "描述",
      form: {
        width: '90%',
        formLabelWidth: formLabelWidth,
        type: 'input',
        itemType: 'textarea',
        rows: 5,
        maxlength: '500', //文本限制输入长度
      }
    },
  ],
})
onMounted(() => {
  getList()
})

function dateChangeHandle(val: any) {
  if (val) {
    searchForm.value.startTime = val[0] + " 00:00:00";
    searchForm.value.endTime = val[1] + " 23:59:59";
  } else {
    searchForm.value.startTime = "";
    searchForm.value.endTime = "";
  }
}
//获取列表
function getList() {
  if(!IsPermission(route, 'QUERY_BASE')){
    ElMessage.error('您没有权限，请联系管理员！')
    return
  }
  crudRef.value.tableLoding = true
  let params: any = {
    pageNo: field.value.paging.currentPage,
    pageSize: field.value.paging.pageSize,
  }
  //赋值查询参数
  let searchFormList = { ...searchForm.value }
  for (let key in searchFormList) {
    if (searchFormList[key]) {
      params[key] = searchFormList[key]
    }
  }
  BaseService.postN('/managew/api/operation/appVersion/page', params).then((res: any) => {
    if (res && res.code === 0) {
      //数据转换
      let bizContent = res.data
      let data = bizContent.result || []
      //数据渲染
      tableData.value = data
      crudRef.value.tableLoding = false
      //分页总数
      field.value.paging.total = bizContent.totalCount
    }
  })
}

const Adds = () => {
  itemStartValue.value = 1
}
//表单编辑按钮
function handleEdit(idx: any, row: any) {
  itemStartValue.value = 2
}

// 添加
const submitAdd = (data: any) => {
  request(data, itemStartValue.value)
}

const request = (data: any, type: any) => {
  //操作类型 1新增 2修改
  BaseService.postN(type == 1 ? '/managew/api/operation/appVersion/add' : '/managew/api/operation/appVersion/update', data).then((res: any) => {
    if (res && res.code === 0) {
      getList()
      crudRef.value.reset();
      crudRef.value.dialogFormVisible = false;
      ElMessage.success('操作成功')
    }
  })
}

// 删除
const deleteHandle = (idx: any, row: any) => {
  BaseService.postN('/managew/api/operation/appVersion/delete', row).then((res: any) => {
    if (res && res.code === 0) {
      getList()
      crudRef.value.reset();
      crudRef.value.dialogFormVisible = false;
    } else {
      ElMessage.error(res.message)
    }
  })
}

//切换按钮
function handleBeforeChange(value: boolean, id: string, row: any) {
  const status = value ? 'ENABLE' : 'DISABLE'
  const statusText = value ? '启用' : '禁用'

  BaseService.post('/managew/api/operation/appVersion/updateStatus', {
    id: id,
    status: status
  }).then((res: any) => {
    if (res && res.code === 0) {
      // 更新本地数据
      row.status = status
      getList()
      ElMessage.success(statusText + "成功");
    } else {
      ElMessage.error(res.message || statusText + "失败")
    }
  }).catch(() => {
    ElMessage.error(statusText + "失败")
  })
}

function downloadHandle() {
}

// 搜索按钮
function btnSearch() {
  field.value.paging.currentPage = 1
  getList()
}

//分页
function handleCurrentChange(val: number) {
  field.value.paging.currentPage = val
  getList()
}
// 搜索重置
function refreshLeft() {
  searchForm.value = {}
  getList()
}

// 取消
function cancel() {

}
</script>
<style scoped>
:deep(.my-content){
  word-break: break-all;
}
</style>
