<!--
 * @Author: 半生瓜 1515706227@qq.com
 * @Date: 2024-05-06 19:31:40
 * @LastEditors: 半生瓜 1515706227@qq.com
 * @LastEditTime: 2024-05-27 23:58:07
 * @FilePath: \vue-element-plus-admin-mini\src\views\zy\Menu12.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { ElInput } from 'element-plus'
import { ref } from 'vue'
import { Dialog } from '@/components/Dialog'
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn, TableSlotDefault } from '@/components/Table'
import { getTemplate, upTemplate, saveTemplate, deleteTemplate } from '@/api/table'
import { reactive, unref } from 'vue'
import { ElButton, ElMessageBox, ElMessage, ElIcon } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { Search, Edit, Delete } from '@element-plus/icons-vue'
import { useValidator } from '@/hooks/web/useValidator'
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { BaseButton } from '@/components/Button'
import { useUserStore } from '@/store/modules/user'
const PATH_URL = window.VITE_API_BASE_PATH

const { required } = useValidator()
const text = ref('')
const userStore = useUserStore()
defineOptions({
  name: 'TemplateManage'
})

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getTemplate({
      page: unref(currentPage),
      pageSize: unref(pageSize),
      name: unref(text)
    })
    return {
      list: res.data.content,
      total: res.data.totalElements
    }
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState

const { refresh, getElTableExpose } = tableMethods

const { t } = useI18n()

const columns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index'
  },
  {
    field: 'zoneName',
    label: '模板名称'
  },
  {
    field: 'updateTime',
    label: '发布时间'
  },

  {
    field: 'action',
    label: t('tableDemo.action'),
    slots: {
      default: (data) => {
        return (
          <>
            <ElButton type="primary" onClick={() => edittab(data)}>
              {t('tableDemo.edit')}
            </ElButton>
            <ElButton type="danger" onClick={() => deletetab(data)}>
              {t('tableDemo.delete')}
            </ElButton>
          </>
        )
      }
    }
  }
])
const imageUrl = ref('')
const isedit = ref('添加')
//删除
const deletetab = async (data: TableSlotDefault) => {
  ElMessageBox.confirm('确定删除该数据?')
    .then(async () => {
      let arr = {
        zoneIds: [data.row.zoneId]
      }
      const res = await deleteTemplate(arr)
      console.log('kkkkkkss', res)
      refresh()
      if (res.code == 200) {
        ElMessage.success('删除成功')
      }
      refresh()
    })
    .catch(() => {
      // catch error
    })
}

const dialogVisible = ref(false)

const Authorization = ref(`Bearer ${userStore.getToken}`)
const headers = ref({ Authorization: Authorization.value })

setInterval(() => {
  Authorization.value = `Bearer ${userStore.getToken}`
  console.log('Authorization', Authorization.value)
  headers.value = { Authorization: Authorization.value }
}, 6000) //

const { formRegister, formMethods } = useForm()
const { getElFormExpose, getFormData } = formMethods

const schema = reactive<FormSchema[]>([
  {
    field: 'zoneName',
    label: '模板名称',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: '请输入模板名称'
    },
    formItemProps: {
      rules: [required()]
    }
  },

  {
    field: 'typeNumber',
    label: '模板内容',
    component: 'Select',
    colProps: {
      span: 24
    },
    componentProps: {
      options: [
        {
          value: 1,
          label: '不含pak包'
        },
        {
          value: 2,
          label: '含pak包'
        }
      ],
      slots: {}
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'thumbnail',
    component: 'Upload',
    label: '模板封面',
    formItemProps: {
      rules: [required()]
    },
    componentProps: {
      action: PATH_URL + '/zone/template/uploadImg',
      headers: headers,
      showFileList: false,
      onSuccess: async (_response, uploadFile) => {
        imageUrl.value = URL.createObjectURL(uploadFile.raw!)
        const formData = await getFormData()
        formData.thumbnail = _response.data
      },
      beforeUpload: (rawFile) => {
        console.log('sadghasgdaj', rawFile.name.includes('jpeg'))
        console.log('kankangeshi', rawFile)
        if (rawFile.name.includes('jpeg')) {
          ElMessage.error('上传格式：png、jpg!')
          return false
        }
        if (rawFile.type !== 'image/png' && rawFile.type !== 'image/jpeg') {
          ElMessage.error('上传格式：png、jpg!')
          return false
        }

        return true
      },
      slots: {
        default: () => (
          <>
            {imageUrl.value ? <img src={imageUrl.value} class="avatar" /> : null}
            {!imageUrl.value ? (
              <ElIcon class="avatar-uploader-icon" size="large" style="font-size: 50px">
                +
              </ElIcon>
            ) : null}
          </>
        ),
        tip: () => <div class="el-upload__tip">上传格式：png、jpg</div>
      }
    }
  },
  {
    field: 'templateFilePath',
    component: 'Upload',
    label: `${t('formDemo.default')}`,
    colProps: {
      span: 24
    },
    formItemProps: {
      rules: [required()]
    },
    componentProps: {
      limit: 1,
      action: PATH_URL + '/zone/template/uploadTemplateZip',
      headers: headers,
      fileList: [],
      multiple: true,
      onPreview: (uploadFile) => {
        console.log('klklkl', uploadFile)
      },
      onRemove: async (file) => {
        console.log(file)
        const formData = await getFormData()
        formData.templateFilePath = ''
        formData.templateFileName = ''
      },
      onSuccess: async (_response, uploadFile) => {
        console.log('kankan_response', uploadFile)
        const formData = await getFormData()
        formData.templateFilePath = _response.data
        formData.templateFileName = uploadFile.name
      },
      beforeUpload: (rawFile) => {
        console.log('kokokoko', rawFile)
        if (rawFile.type !== 'application/x-zip-compressed' && rawFile.type !== 'application/zip') {
          ElMessage.error('只能上传ZIP文件')
          return false
        }
        return true
      },
      slots: {
        default: () => <BaseButton type="primary">点击上传</BaseButton>,
        tip: () => <div class="el-upload__tip">只能上传ZIP文件</div>
      }
    }
  }
])

//编辑
const edittab = async (data: TableSlotDefault) => {
  console.log('shanchu', data)
  isedit.value = '编辑'
  dialogVisible.value = true
  const formRef = await getElFormExpose()
  const formData = await getFormData()
  formData.zoneName = data.row.zoneName
  formData.templateFileName = data.row.templateFileName
  formData.templateFilePath = data.row.templateFilePath
  formData.thumbnail = data.row.thumbnail
  formData.pakPath = data.row.pakPath
  imageUrl.value = PATH_URL + data.row.thumbnail
  formData.zoneId = data.row.zoneId
  formData.typeNumber = data.row.typeNumber
  schema[3].componentProps.fileList = [
    {
      name: data.row.templateFileName,
      url: data.row.templateFilePath
    }
  ]
}
// 添加编辑模板管理
const signIn = async () => {
  const formRef = await getElFormExpose()
  const formData = await getFormData()
  console.log('kakkkkak', formData)
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      const res = await saveTemplate(formData)
      console.log('kankansss', res)

      if (res) {
        dialogVisible.value = false
        refresh()
      } else {
        ElMessage.error(res)
      }
    }
  })
}

//搜索
const handersearch = function () {
  tableState.currentPage.value = 1
  refresh()
}

//多选删除
const getSelections = async () => {
  const elTableRef = await getElTableExpose()
  const selections = elTableRef?.getSelectionRows()

  let arr = {
    zoneIds: []
  }
  if (selections) {
    arr.zoneIds = selections.map((item) => {
      return item.zoneId
    })
  }
  if (arr.zoneIds.length !== 0) {
    ElMessageBox.confirm('确定删除所选数据?')
      .then(async () => {
        console.log('kankan', arr)
        const res = await deleteTemplate(arr)
        console.log('kkkkkkss', res)
        if (res.code == 200) {
          ElMessage.success('删除成功')
        }
        refresh()
      })
      .catch(() => {
        // catch error
      })
  } else {
    ElMessage.warning('请选择数据')
  }
}
const tianjia = async () => {
  isedit.value = '添加'
  imageUrl.value = ''
  schema[2].componentProps.fileList = []
  dialogVisible.value = true
}
</script>

<template>
  <ContentWrap>
    <div style="margin-bottom: 10px">
      <span style="color: #606266"> {{ t('levelDemo.menu') }}：</span>
      <el-input
        v-model="text"
        style="width: 200px; height: 43px; margin: 7px"
        placeholder="请输入模板名称"
      />
      <ElButton type="primary" size="large" @click="handersearch" :icon="Search">搜索</ElButton>
      <ElButton type="success" size="large" @click="tianjia" :icon="Edit">添加</ElButton>
      <ElButton type="danger" size="large" @click="getSelections" :icon="Delete">删除</ElButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      row-key="id"
      headerAlign="center"
      align="center"
      :loading="loading"
      sortable
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      @refresh="refresh"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" maxHeight="430px" width="35rem" :title="isedit">
    <Form :schema="schema" @register="formRegister" />

    <template #footer>
      <div style="width: 100%; display: flex; justify-content: center">
        <BaseButton
          style="font-size: 1rem; height: 2.2rem; margin: auto"
          type="primary"
          class="w-[15%]"
          @click="signIn"
        >
          确定
        </BaseButton>
      </div>
    </template>
  </Dialog>
</template>

<style lang="less">
.el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  width: 120px;
  height: 120px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
}
</style>
