<template>
  <div class="app-container">
    <el-row :gutter="30">
      <el-col :span="6">
        <el-card class="mb10">
          <template #header>
            <p>推送平台</p>
          </template>
          <div class="p-10px">
            <el-radio-group v-model="platform" @change="handlePlatformChange">
              <template v-for="item in platformList">
                <el-radio :value="item.id">{{ platformDict[item.type] }}</el-radio>
              </template>
            </el-radio-group>
          </div>
        </el-card>
        <el-card>
          <template #header>
            <p>推送模板</p>
          </template>
          <div class="p-10px">
            <el-radio-group v-model="tmpl" @change="handleTmplChange">
              <template v-for="item in tmplList">
                <el-radio :value="item.id"><div v-html="formateTmpl(item.content)"></div></el-radio>
              </template>
            </el-radio-group>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户昵称" prop="nickname">
            <el-input
              v-model="queryParams.nickname"
              placeholder="请输入用户昵称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="openId" prop="openId">
            <el-input
              v-model="queryParams.openId"
              placeholder="请输入openId"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['business:member:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['business:member:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['business:member:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['business:member:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="用户昵称" align="center" prop="nickname" />
          <el-table-column label="用户头像" align="center" prop="avatarUrl" width="100">
            <template #default="scope">
              <image-preview :src="scope.row.avatarUrl" :width="50" :height="50"/>
            </template>
          </el-table-column>
          <el-table-column label="性别" align="center" prop="gender" />
          <el-table-column label="手机号" align="center" prop="mobile" />
          <el-table-column label="openId" align="center" prop="openId" />
          <el-table-column label="unionId" align="center" prop="unionId" />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:member:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:member:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改虫情预警推送人员接收列对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="memberRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="用户头像" prop="avatarUrl">
          <image-upload :limit="1" v-model="form.avatarUrl"/>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Member">
import { listMember, getMember, delMember, addMember, updateMember } from "@/api/memberPush"
import { listPushPlatform, listPushTemplate, updatePushPlatform, updatePushTemplate } from "@/api/pushSetting"

const { proxy } = getCurrentInstance()

const memberList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const platform = ref(0)
const tmpl = ref(0)
const platformList = ref([])
const tmplList = ref([])
const platformDict = {
  0: "公众号",
  1: "短信"
}

const tmplDict = {
  thing3: "项目名称",
  thing20: "企业名称",
  thing44: "对应点位",
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nickname: null,
    mobile: null,
    openId: null,
  },
  rules: {
    nickname: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" }
    ],
    mobile: [
      { required: true, message: "手机号不能为空", trigger: "blur" }
    ],
    openId: [
      { required: true, message: "openId不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询虫情预警推送人员接收列列表 */
function getList() {
  loading.value = true
  listMember(queryParams.value).then(response => {
    memberList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询推送平台列表 */
function getPlatformList() {
  listPushPlatform().then(response => {
    platformList.value = response.rows
    setDefaultPlatform(response.rows)
  })
}

/** 查询推送模板列表 */
function getTmplList() {
  listPushTemplate().then(response => {
    tmplList.value = response.rows
    setDefaultTmpl(response.rows)
  })
}

function setDefaultPlatform(list) {
  if (!list.length) return;
  const res = list.find(item => item.status == 1)
  res && (platform.value = res.id)
}

function setDefaultTmpl(list) {
  if (!list.length) return;
  const res = list.find(item => item.status == 1)
  console.log(res)
  res && (tmpl.value = res.id)
}

function formateTmpl(content) {
  const tmpl = JSON.parse(content)
  let contentText = ''
  Object.keys(tmplDict).forEach(key => {
    const keyText = tmplDict[key] || key
    contentText += `<p>${keyText}：${tmpl[key]}</p>`
  })
  return contentText;
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    nickname: null,
    avatarUrl: null,
    gender: null,
    country: null,
    province: null,
    city: null,
    mobile: null,
    openId: null,
    unionId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  proxy.resetForm("memberRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加虫情预警推送人员接收列"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getMember(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改虫情预警推送人员接收列"
  })
}

/** 推送平台选择改变 */
function handlePlatformChange(id) {
  const item = platformList.value.find(item => item.id == id)
  const form = Object.assign(item, {
    status: 1
  })
  updatePushPlatform(form).then(() => {
    proxy.$modal.msgSuccess("修改成功")
  })
}

/** 推送模板选择改变 */
function handleTmplChange(id) {
  const item = tmplList.value.find(item => item.id == id)
  const form = Object.assign(item, {
    status: 1
  })
  updatePushTemplate(form).then(() => {
    proxy.$modal.msgSuccess("修改成功")
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["memberRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMember(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMember(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除虫情预警推送人员接收列编号为"' + _ids + '"的数据项？').then(function() {
    return delMember(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
async function handleExport() {
  // proxy.download('business/member/export', {
  //   ...queryParams.value
  // }, `推送人员_${new Date().getTime()}.xlsx`)
  const fileName = await proxy.download('/business/member/export', queryParams.value, `推送人员数据_${new Date().getTime()}.xlsx`)
  fileName && proxy.$download.name(fileName)
}

getList()
getPlatformList()
getTmplList()
</script>
