<template>
  <div class="mainContentBox">
    <avue-crud
        ref="crudRef"
        v-model:search="search"
        v-model="form"
        :data="data"
        :option="option"
        v-model:page="page"
        @row-save="createRow"
        @row-update="updateRow"
        @row-del="deleteRow"
        @search-change="searchChange"
        @search-reset="resetChange"
        @size-change="dataList"
        @current-change="dataList"
        @selection-change="selectionChange"
    >
      <template #menu-left="{ size }">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :size="size"
          @click="messageDialog"
          >新增</el-button
        >
      </template>
      <template #menu="{size,row,index}">
        <el-button
            v-if="row.state === '0'"
            type="primary"
            link
            size="small"
            @click="handleEdit(row,0)"
        ><i-ep-edit />编辑
        </el-button>

        <el-button
            type="primary"
            link
            v-if="row.state === '0'"
            size="small"
            @click="handleSend(row,0)"
        ><i-ep-edit />发送
        </el-button>
      </template>
    </avue-crud>
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="800px"
        @close="dialog.visible = false"
    >
      <el-form
          ref="userFormRef"
          :model="message"
          :rules="rules"
          label-width="90px"
      >
        <el-row :gutter="22">
          <el-col :span="11">
            <el-form-item label="标题" prop="title">
              <el-input class="!w-[220px]" v-model="message.title" placeholder="请输入标题" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="类型" prop="type">
              <el-select
                  disabled
                  v-model="message.type"
                  placeholder="类型"
                  clearable
                  class="!w-[220px]"
              >
                <el-option
                    v-for="item in messageTypes"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="22" v-if="message.type === '1'">
          <el-col :span="22">
            <el-form-item label="接收人员" prop="receiveUsers">
              <el-select
                  v-model="message.receiveUsers"
                  placeholder="类型"
                  clearable
                  multiple
                  filterable
                  class="!w-[500px]"
              >
                <el-option
                    v-for="item in userList"
                    :key="item.id"
                    :label="item.userName"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="22">
          <el-col :span="22">
            <el-form-item label="内容" prop="content">
              <Editor :value="editorContent" @updateValue="getMsg" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="dialog-footer" align="center">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import Editor from '@/views/system/message/editor/index.vue'
import {addMessage, updateMessage} from '@/api/system/message'
import { useCommonStoreHook } from "@/store";
import {getUserList} from "@/api/system/user"
import {queryDictDataByType} from "@/api/system/dict"
const { isShowTable, tableType } = toRefs(useCommonStoreHook());
const userFormRef = ref(ElForm); // 用户表单
const message = ref({
  title: "",
  content: "",
  type: "0",
  receiveUsers: []
});
const test = () => {
  isShowTable.value = true;
  tableType.value = tableType.value == 1 ? 2 : 1;
};
const  handleSubmit = ()=>{
  userFormRef.value.validate((valid) => {
    if (valid) {
      if(message.value.id){
        updateMessage(message.value).then((data)=>{
          if(data.code === '200'){
            ElMessage.success(data.msg)
            dialog.visible = false
            dataList()
          }else{
            ElMessage.error(data.msg)
          }
        })
      }else{
        addMessage(message.value).then((data)=>{
          if(data.code === '200'){
            ElMessage.success(data.msg)
            dialog.visible = false
            dataList()
          }else{
            ElMessage.error(data.msg)
          }
        })
      }
    }
  });
}
const handleEdit =(row,index)=>{
  message.value = row
  editorContent.value = row.content
  dialog.visible = true
}
const handleSend =(row,index)=>{
  ElMessageBox.confirm("确定要发送吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    lockScroll: false,
  }).then(() => {
    row.state = 1
    updateMessage(row).then((data)=>{
      if(data.code === '200'){
        ElMessage.success(data.msg)
        dialog.visible = false
        dataList()
      }else{
        ElMessage.error(data.msg)
      }
    })
  });
}
const editorContent = ref(null)
const crudRef = ref(null); //crudRef.value 获取avue-crud对象
const dialog = reactive({
  title: "消息管理",
  visible: false,
  type: "0",
  state: "0"
});

const rules = reactive({
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
  receiveUsers: [{ required: true, message: "人员不能为空", trigger: "blur" }],
});
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/sys/message",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } = Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具

const getMsg =(val)=>{
  message.value.content = val
}
const messageDialog = ()=>{
  message.value.title = ''
  message.value.content = ''
  message.value.receiveUsers = []
  editorContent.value = ""
  dialog.visible = true
}
const messageTypes = ref([])
const userList = ref([])
const queryUserList = ()=>{
  getUserList({}).then((data)=>{
    userList.value = data.data
  })
  queryDictDataByType("system_message_type").then((data)=>{
    messageTypes.value = data.data
  })
}
// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  delBtn: false,
  selection: false,
  addBtn: false,
  editBtn: false,
  viewBtn: false,
  column: [
    {
      label: "标题",
      prop: "title",
      rules: [
        {
          required: true,
          message: "标题不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "内容",
      prop: "content",
      width: 300,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "内容不能为空",
          trigger: "trigger",
        },
      ],
      html: true,
      formatter: (val) => {
        return val.content;
      },
    },
    {
      label: "类型",
      prop: "type",
      overHidden: true,
      type: 'select',
      width: 150,
      dicData: [{label: '系统消息',value: '0'},{label: '用户消息',value:'1'}],
      rules: [
        {
          required: true,
          message: "类型不能为空",
          trigger: "trigger",
        },
      ],
      html: true,
      formatter: (val) => {
        if (val.type === "0") {
          return '<b class="el-tag el-tag--danger el-tag--light">系统消息</b>';
        } else if (val.type === "1") {
          return '<b class="el-tag el-tag--success el-tag--light">用户消息</b>';
        }
      },
    },
    {
      label: "状态",
      prop: "state",
      display: false,
      width: 150,
      dicData: [{label: '暂存',value: '0'},{label: '已发送',value:'1'}],
      html: true,
      formatter: (val) => {
        if (val.state === "0") {
          return '<b class="el-tag el-tag--warning el-tag--light">暂存</b>';
        } else if (val.state === "1") {
          return '<b class="el-tag el-tag--success el-tag--light">已发送</b>';
        }
      },
    },
    {
      label: "创建人",
      prop: "creator",
      display: false,
    },
    {
      label: "创建时间",
      prop: "created",
      display: false,
    },
  ],
});

onMounted(() => {
  // console.log("crudRef", crudRef)
  search.value.type = "0"
  search.value.msgId = "0"
  dataList();
  queryUserList()
});
</script>
