<template>
  <div class="system-edit-post-container">
    <el-form size="default" label-width="100px">
      <el-form-item label="服务器" prop="serverId">
        <el-select v-model="serverSwitch" class="m-2" placeholder="选择服务器" size="large" style="width: 80px">
          <el-option v-for="item in serverCategorize" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-select v-model="queryParams.serverId" multiple class="m-2" placeholder="选择服务器" size="large">
          <el-option v-for="item in switchServer()" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <!--            <el-form-item label="附件" prop="type">-->
      <!--                <el-radio-group v-model="queryParams.type" @change="showDrop">-->
      <!--                    <el-radio :label="1">有附件</el-radio>-->
      <!--                    <el-radio :label="2">无附件</el-radio>-->
      <!--                </el-radio-group>-->
      <!--            </el-form-item>-->
      <el-form-item label="有效期限" prop="expired">
        <el-radio-group v-model="queryParams.expired">
          <el-radio :label="1">过期删除</el-radio>
          <el-radio :label="2">无限制</el-radio>
        </el-radio-group>
        <span v-if="queryParams.expired==1" style="margin-left: 50px">
          <el-input-number v-model="queryParams.validDay" placeholder="请输入有效天数" controls-position="right"
                           onkeyup="this.value=this.value.replace(/\D/g,'');"
                           onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
        </span>
        <span v-show="queryParams.expired==1&&!queryParams.validDay" style="color: red; margin-left: 5px">*</span>
      </el-form-item>
      <el-form-item label="新号可领" prop="newGet">
        <el-radio-group v-model="queryParams.newGet">
          <el-radio :label="1">不可领取</el-radio>
          <el-radio :label="2">可以领取</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-card shadow="hover" header="邮件内容">
        <el-form-item>
          <el-select v-model="queryParams.contentModel" @change="useModel(2)" placeholder="请选择模板">
            <el-option v-for="item in contentModels" :key="item.id" :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
          <el-button type="primary" @click="makeModel(2)" style="margin-left: 20px">编辑模板</el-button>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="queryParams.title" placeholder="请输入邮件标题" style="width: 300px"/>
          <span v-show="!queryParams.title" style="color: red; margin-left: 5px">*</span>
        </el-form-item>
        <el-form-item label="发件人署名" prop="from">
          <el-input v-model="queryParams.from" placeholder="请输入发件人署名" style="width: 300px"/>
          <span v-show="!queryParams.from" style="color: red; margin-left: 5px">*</span>
        </el-form-item>
        <!--        <el-form-item label="收件人称谓" prop="content">-->
        <!--          <el-input v-model="queryParams.to" placeholder="请输入收件人称谓" style="width: 300px"/>-->
        <!--          &lt;!&ndash;          <span v-show="!queryParams.to" style="color: red; margin-left: 5px">*</span>&ndash;&gt;-->
        <!--        </el-form-item>-->
        <!--                <el-form-item label="问候语" prop="greetings">-->
        <!--                    <el-input v-model="queryParams.greetings" placeholder="请输入问候语" style="width: 300px"/>-->
        <!--                    <span v-show="!queryParams.greetings" style="color: red; margin-left: 5px">*</span>-->
        <!--                </el-form-item>-->
        <el-form-item label="内容" prop="content">
          <el-input v-model="queryParams.content" type="textarea" :autosize="{ minRows: 2}" placeholder="请输入内容"
                    style="width: 600px"/>
          <span v-show="!queryParams.content" style="color: red; margin-left: 5px">*</span>
        </el-form-item>
      </el-card>
      <el-card shadow="hover" header="收件人">
        <el-radio-group v-model="queryParams.toAll" @change="showTo">
          <el-radio :label="1">全服</el-radio>
          <el-radio :label="2">指定</el-radio>
        </el-radio-group>
        <el-tooltip placement="top-start" content="用分号';'分开" v-if="isShowTo">
          <el-input v-if="isShowTo" v-model="queryParams.ownerId" type="textarea" placeholder="请输入收件人uid"/>
        </el-tooltip>
      </el-card>
      <el-card shadow="hover" header="附件">
        <el-form-item>
          <el-select v-model="queryParams.dropModel" @change="useModel(1)" placeholder="请选择模板"
                     popper-class="custom-header">
            <template #header>
              <el-button type="primary" @click="makeModel(1)" style="margin-left: 20px">编辑模板</el-button>
            </template>
            <el-option v-for="item in dropModels" :key="item.id" :label="item.name" :value="item.id">
              {{ item.name }}
            </el-option>
          </el-select>
          <el-button type="primary" @click="makeModel(1)" style="margin-left: 20px">编辑模板</el-button>
        </el-form-item>
        <el-table :data="queryParams.drops" :inline="true" :cell-style="{padding:'0'}" :table-layout="'auto'">
          <el-table-column width="30">
            <template #default="scope">
              <div class="flex-warp">
                <el-button size="small" type="text" @click="delItem(scope.$index)">
                  <el-icon>
                    <ele-Minus/>
                  </el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="60" label="序号">
            <template #default="scope">
              <div class="flex-warp">{{ scope.$index + 1 }}</div>
            </template>
          </el-table-column>
          <el-table-column label="物品">
            <template #default="scope">
              <div class="flex-warp">
                <el-select v-model="scope.row.id" filterable placeholder="请选择物品">
                  <el-option v-for="item in ItemConfig" :key="item.Id" :label="item.Id+' '+item.DetailsPageName"
                             :value="item.Id"/>
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="数量">
            <template #default="scope">
              <div class="flex-warp">
                <el-input v-model="scope.row.num" placeholder="请输入数量" style="width: 300px"
                          onkeyup="this.value=this.value.replace(/\D/g,'');"
                          onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-button size="default" type="primary" style="margin: 10px 0" @click="addItem()">
          <el-icon>
            <ele-Plus/>
          </el-icon>
          添加
        </el-button>
      </el-card>
      <el-card shadow="hover" header="发送设置">
        <el-radio-group v-model="queryParams.send" @change="showSend">
          <el-radio :label="4">10分钟后发送</el-radio>
          <el-radio :label="2">定时发送</el-radio>
          <el-radio :label="1">立刻发送</el-radio>
        </el-radio-group>
        <el-form-item prop="now" v-if="isShowSend">
          <el-date-picker type="datetime" v-model="queryParams.sendTime" placeholder="发送时间"
                          format="YYYY-MM-DD HH:mm:ss"
                          value-format="x"/>
        </el-form-item>
      </el-card>
      <el-form-item>
        <el-button size="default" type="primary" @click="onOpenEditDic"
                   :disabled="!sendMail||!queryParams.content||!queryParams.from||!queryParams.title
                   ||(queryParams.toAll===2&&!queryParams.ownerId)">
          发送邮件
        </el-button>
      </el-form-item>
    </el-form>

    <el-dialog v-model="listModelVisible" :show-close="false" :before-close="handleClose" center>
      <div class="my-header">
        <el-button type="" @click="saveModel(2)">保存</el-button>
        <el-button type="primary" @click="setModel(1)">添加</el-button>
      </div>
      <el-table :data="models" :inline="true" :cell-style="{padding:'0'}">
        <el-table-column>
          <template #default="scope">
            <div class="flex-warp">
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column width="150">
          <template #default="scope">
            <el-button size="small" type="danger" @click="setModel(3,scope.row.id)" inline="true">删
            </el-button>
            <el-button size="small" type="primary" @click="setModel(2,scope.row.id)" inline="true">改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog v-model="editModelVisible" center>
      <el-form label-width="90px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="model.name" placeholder="请输入模板名称" style="width: 300px"/>
        </el-form-item>
        <el-form-item v-if="modelType == 2" label="标题" prop="title">
          <el-input v-model="model.title" placeholder="请输入邮件标题" style="width: 300px"/>
        </el-form-item>
        <el-form-item v-if="modelType == 2" label="发件人署名" prop="from">
          <el-input v-model="model.from" placeholder="请输入发件人署名" style="width: 300px"/>
        </el-form-item>
        <!--                <el-form-item v-if="modelType == 2" label="问候语" prop="greetings">-->
        <!--                    <el-input v-model="model.greetings" placeholder="请输入问候语" style="width: 300px"/>-->
        <!--                </el-form-item>-->
        <el-form-item v-if="modelType == 2" label="内容" prop="content">
          <el-input v-model="model.content" type="textarea" placeholder="请输入内容" style="width: 300px"/>
        </el-form-item>
      </el-form>
      <el-table v-if="modelType == 1" :data="model.drops" :inline="true" :cell-style="{padding:'0'}"
                table-layout="auto">
        <el-table-column width="30">
          <template #default="scope">
            <div class="flex-warp">
              <el-button size="small" type="text" @click="delModelItem(scope.$index)">
                <el-icon>
                  <ele-Minus/>
                </el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column>
          <template #default="scope">
            <div class="flex-warp">
              {{ scope.$index + 1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="物品">
          <template #default="scope">
            <div class="flex-warp">
              <el-select v-model="scope.row.id" filterable placeholder="请选择物品">
                <el-option v-for="item in ItemConfig" :key="item.Id" :label="item.Id +' '+ item.DetailsPageName"
                           :value="item.Id"/>
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="数量">
          <template #default="scope">
            <div class="flex-warp">
              <el-input v-model="scope.row.num" placeholder="请输入数量" style="width: 300px"
                        onkeyup="this.value=this.value.replace(/\D/g,'');"
                        onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="modelType == 1">
        <el-button v-if="modelType == 1" size="default" type="primary" @click="addModelItem()">
          <el-icon>
            <ele-Plus/>
          </el-icon>
          添加
        </el-button>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveModel(1)">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <EditConfig ref="editDicRef" @countList="onSubmit"/>
  </div>
</template>

<script lang="ts">
import {reactive, toRefs, defineComponent, ref, onMounted} from 'vue';
import {gameMailSend, gameGetModel, gameUpdateModel} from '/@/api/game';
import EditConfig from '/@/views/gameMail/send/component/editConfig.vue';
import {ServerCategorize, serverList} from "/@/utils/game";
import AllItemConfigCategory from "/@/api/config/AllItemConfigCategory.json";
import {ElMessage, ElMessageBox} from "element-plus";
import {Session} from "/@/utils/storage";
import {getCookie, gSwitchServer} from "/@/utils/utils";

interface QueryParams {
  serverId: string[]
  type: number
  validDay: number
  expired: number
  newGet: number
  title: string
  from: string
  // greetings: string
  contentModel: number
  content: string
  toAll: number
  ownerId: string
  dropModel: number
  drops: object[]
  send: number
  sendTime: number
}

interface TableDataState {
  cookie: string,
  queryParams: QueryParams;
  dropModels: object[];
  contentModels: object[];
  models: object[];
  model: object;
  modelType: number;
  servers: object;
  ItemConfig: object;
  isShowTo: boolean;
  isShowSend: boolean;
  listModelVisible: boolean;
  editModelVisible: boolean;
  sendMail: boolean;
  serverSwitch: number;
  serverCategorize: object;
}

export default defineComponent({
  name: 'apiV1GameMailSend',
  components: {EditConfig},
  setup() {
    const editDicRef = ref();
    const state = reactive<TableDataState>({
      serverSwitch: 0,
      cookie: "",
      isShowTo: false,
      isShowSend: false,
      listModelVisible: false,
      editModelVisible: false,
      ItemConfig: AllItemConfigCategory,
      models: [],
      model: {},
      modelType: 0,
      queryParams: {
        serverId: [],
        type: 1,
        validDay: 10,
        expired: 1,
        newGet: 1,
        title: "",
        from: "小桃子",
        // greetings: "",
        contentModel: "",
        dropModel: "",
        content: "",
        ownerId: "",
        toAll: 1,
        drops: [],
        send: 4,
        sendTime: new Date().getTime(),
      },
      servers: {},
      dropModels: [],
      contentModels: [],
      sendMail: true,
      serverCategorize: ServerCategorize
    });
    onMounted(() => {
      serverList().then(value => {
        state.servers = value;
        state.queryParams.serverId[0] = value[0].id;
        // console.log(" server : ", state.servers);
      });
      getMailModel(1);
      getMailModel(2);
    });
    // 新增
    const onSubmit = () => {
      if (!state.sendMail) {
        ElMessage.error('邮件已发送');
        return;
      }
      state.sendMail = false;

      if (state.queryParams.expired == 1 && state.queryParams.validDay == 0) {
        ElMessage.error('过期天数未填写！');
        return;
      }
      let mail = onState();
      var userInfo = Session.get("userInfo");
      for (let i = 0; i < mail.drops; i++) {
        if (!mail.drops[i].num) {
          ElMessage.error('奖励数量未配置');
          return;
        }
      }

      console.log("mail>>>>>>", mail);
      console.log("userInfo: ", userInfo);
      mail["userName"] = userInfo.userName;
      gameMailSend(mail).then(() => {
        resetForm();
        console.log("userInfo: 邮件发送成功", userInfo);
        ElMessage.success('邮件发送成功');
      }).finally(() => {
        setTimeout(function () {
          state.sendMail = true;
        }, 5000);
      })
    };
    const onState = () => {
      let mail = {
        isAll: (state.queryParams.toAll == 1 ? true : false),
        serverId: state.queryParams.serverId,
        from: state.queryParams.from,
        type: state.queryParams.type,
        send: state.queryParams.send,
        sendTime: new Date().getTime(),
        validDay: state.queryParams.validDay,
        expired: state.queryParams.expired,
        newGet: state.queryParams.newGet,
        title: state.queryParams.title,
        ownerId: state.queryParams.ownerId,
        // greetings: "",
        content: state.queryParams.content,
        drops: state.queryParams.drops,
      };
      if (state.queryParams.toAll == 1) {
        state.queryParams.ownerId = "";
      }

      for (let i in mail.drops) {
        mail.drops[i].id = Number(mail.drops[i].id);
        mail.drops[i].num = Number(mail.drops[i].num);
      }
      if (mail.drops.length > 0) {
        mail.type = 1
      } else {
        mail.type = 2
      }
      return mail;
    };

    const resetForm = () => {
      let serverId = [];
      if (parent.document.cookie) {
        console.log("state.cookie", parent.document.cookie, getCookie(parent.document.cookie, "serverId"));
        serverId = JSON.parse(getCookie(parent.document.cookie, "serverId"))
      }

      console.log("serverId", serverId);
      state.queryParams = {
        serverId: serverId,
        type: 1,
        validDay: 10,
        expired: 1,
        newGet: 1,
        title: "",
        from: "小桃子",
        // greetings: "",
        contentModel: "",
        dropModel: "",
        content: "",
        ownerId: "",
        toAll: 1,
        drops: [],
        send: 4,
        sendTime: new Date().getTime(),
      }
    };
    const showTo = () => {
      if (state.queryParams.toAll == 2) {
        state.isShowTo = true;
      } else {
        state.isShowTo = false;
      }
    };
    const showSend = () => {
      if (state.queryParams.send == 2) {
        state.isShowSend = true;
      } else {
        state.isShowSend = false;
      }
    };

    const getMailModel = (type: number) => {
      gameGetModel({mType: type}).then(function (res) {
        if (res && res.data && res.data.model) {
          if (type == 1) {
            state.dropModels = JSON.parse(res.data.model);
          } else if (type == 2) {
            state.contentModels = JSON.parse(res.data.model);
          }
        } else {
          if (type == 1) {
            state.dropModels = [];
          } else if (type == 2) {
            state.contentModels = [];
          }
        }
      })
    };
    const useModel = (type: number) => {
      switch (type) {
        case 1:
          let model = state.dropModels.find(r => r.id == state.queryParams.dropModel);
          if (model) {
            state.queryParams.drops = [];
            for (let i in model.drops) {
              let drop = model.drops[i];
              let data = {id: drop.id, num: drop.num};
              state.queryParams.drops.push(data);
            }
          }
          break;
        case 2:
          let model1 = state.contentModels.find(r => r.id == state.queryParams.contentModel);
          if (model1) {
            state.queryParams.title = model1.title;
            state.queryParams.content = model1.content;
            // state.queryParams.greetings = model1.greetings;
            state.queryParams.from = model1.from;
          }
          break;
      }
    };
    const makeModel = (type: number) => {
      state.models = [];
      switch (type) {
        case 1:
          state.models = state.dropModels;
          state.modelType = 1;
          state.listModelVisible = true;
          break;
        case 2:
          state.models = state.contentModels;
          state.modelType = 2;
          state.listModelVisible = true;
          break;
      }
      console.log(type, state);
    };
    const setModel = (type: number, id: number) => {
      state.model = {};
      switch (type) {
        case 1:
          //   switch(state.modelType){
          //     case 1:
          //       state.editModelVisible = true;
          //       break;
          //     case 2:
          state.editModelVisible = true;
          //     break;
          // }
          break;
        case 2:
          switch (state.modelType) {
            case 1:
              state.model = state.dropModels.find(model => model.id == id);
              state.editModelVisible = true;
              break;
            case 2:
              state.model = state.contentModels.find(model => model.id == id);
              state.editModelVisible = true;
              break;
          }
          break;
        case 3:
          state.models = [];
          switch (state.modelType) {
            case 1:
              state.dropModels = state.dropModels.filter(model => model.id != id);
              for (let i = 0; i < state.dropModels.length; i++) {
                let dropModel = state.dropModels[i];
                if (dropModel) {
                  dropModel.id = i + 1;
                }
              }
              state.models = state.dropModels;
              break;
            case 2:
              state.contentModels = state.contentModels.filter(model => model.id != id);
              for (let i = 0; i < state.contentModels.length; i++) {
                let contentModel = state.contentModels[i];
                if (contentModel) {
                  contentModel.id = i + 1;
                }
              }
              state.models = state.contentModels;
              break;
          }
          break;
      }
    };
    const saveModel = (type: number) => {
      console.log(type, state.model);
      switch (type) {
        case 1:
          state.editModelVisible = false;
          if (state.model.id) {
            return
          }

          state.models.push(state.model);
          switch (state.modelType) {
            case 1:
              state.dropModels = state.models;
              break;
            case 2:
              state.contentModels = state.models;
              break;
          }
          state.model.id = state.models.length;
          break;
        case 2:
          gameUpdateModel({
            mType: state.modelType,
            model: JSON.stringify(state.models)
          }).then(function () {
          }).finally(function () {
            state.listModelVisible = false;
          });
          break;
      }
    };

    const handleClose = (done: () => void) => {
      ElMessageBox.confirm('确定退出编辑模板页面？').then(() => {
        done()
      }).catch(() => {
        // catch error
      })
    };

    const delModelItem = (index: number) => {
      state.model.drops.splice(index, 1);
    };
    const addModelItem = () => {
      let item = {};
      if (!state.model.drops) {
        state.model.drops = [];
      }
      state.model.drops.push(item);
    };

    const delItem = (index: number) => {
      state.queryParams.drops.splice(index, 1);
    };
    const addItem = () => {
      let item = {};
      if (!state.queryParams.drops) {
        state.queryParams.drops = [];
      }
      state.queryParams.drops.push(item);
    };
    // 打开修改字典弹窗
    const onOpenEditDic = () => {
      parent.document.cookie = "serverId=" + JSON.stringify(state.queryParams.serverId);
      editDicRef.value.openDialog(state.queryParams, state.servers);
    };

    const switchServer = () => {
      return gSwitchServer(state.serverSwitch, state.servers)
    };
    return {
      switchServer,
      onSubmit,
      editDicRef,
      showTo,
      showSend,
      resetForm,
      useModel,
      makeModel,
      setModel,
      saveModel,
      delModelItem,
      addModelItem,
      handleClose,
      addItem,
      delItem,
      onOpenEditDic,
      ...toRefs(state),
    };
  },
});
</script>
<style scoped lang="scss">
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16px;
}

.tree-border {
  margin-top: 5px;
  border: 1px solid #e5e6e7 !important;
  background: #fff none !important;
  border-radius: 4px;
}

.system-edit-post-container {
  .menu-data-tree {
    border: var(--el-input-border, var(--el-border-base));
    border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
    padding: 5px;
  }
}
</style>
