<template>
  <div class="page-container column-container">
    <!-- 搜索区 -->
    <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch"
      label-width="68px">
      <el-form-item class="section-title" label="邮箱配置" />
      <el-form-item label="邮箱地址：" prop="emailAddress">
        <el-input v-model.trim="queryParams.emailAddress" placeholder="请输入邮箱地址" clearable style="width: 186px"
          @keyup.enter="handleQueryUser" />
      </el-form-item>
      <el-form-item label="邮箱类型：" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择" clearable style="width: 100%;">
          <el-option v-for="dict in emailType" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="info" icon="Search" @click="handleQueryUser">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-button type="primary" icon="Plus" @click="handleShowUserDialog(null)"
        v-hasPermi="['system:email:add']">新增</el-button>
      <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDeleteMultipleUser"
        v-hasPermi="['system:email:remove']">删除</el-button>
    </div>
    <!-- 渲染数据区 -->
    <div class="el-table-container">
      <div class="el-table-inner-container">
        <el-table v-loading="loading" :data="userList" height="100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="40" align="center" />
          <el-table-column label="邮箱类型" align="center" prop="type">
            <!-- 寄件，收件 -->
            <template #default="scope">
              <el-tag v-if="scope.row.type == 1" type="success">收件</el-tag>
              <el-tag v-else type="danger">寄件</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="isStop">
            <template #default="scope">
              <el-tag v-if="scope.row.isStop == 0" type="success">启用</el-tag>
              <el-tag v-else type="danger">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="邮箱地址" align="center" prop="emailAddress" />
          <el-table-column label="授权码" align="center" prop="authCode">
            <template #default="scope">{{ scope.row.authCode ? '******' : '' }}</template>
          </el-table-column>
          <el-table-column label="端口" align="center" prop="port" />
          <el-table-column label="发送协议" align="center" prop="protocol" />
          <el-table-column label="协议服务地址" align="center" prop="host" />
          <el-table-column label="是否使用ssl" align="center" prop="ssl">
            <template #default="scope">
              <el-tag v-if="scope.row.ssl == 1" type="success">是</el-tag>
              <el-tag v-else type="danger">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" width="220">
            <template #default="scope">
              <el-button link type="warning" icon="Edit" @click="handleShowUserDialog(scope.row.id)"
                v-hasPermi="['system:email:edit']">编辑</el-button>
              <el-button link type="danger" icon="Delete" @click="handleDeleteUser(scope.row.id)"
                v-hasPermi="['system:email:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog title="邮箱信息" v-model="open" width="450px" append-to-body draggable>
      <div class="form-container">
        <el-form ref="userRef" :model="form" class="master-container" :rules="rules" label-width="110px">
          <el-form-item label="邮箱类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择" clearable style="width: 100%;">
              <el-option v-for="dict in emailType" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="邮箱地址" prop="emailAddress">
            <el-input v-model.trim="form.emailAddress" placeholder="请输入邮箱地址" />
          </el-form-item>
          <el-form-item label="授权码" prop="authCode">
            <template #label>
              <el-popover placement="top-start" effect="dark" trigger="hover" content="此端口是寄件邮箱授权码，只有寄件邮箱需要填写">
                <template #reference>
                  <el-icon style="display: inline-block;line-height: 36px; height: 36px;">
                    <QuestionFilled />
                  </el-icon>
                </template>
              </el-popover>
              <div>授权码</div>
            </template>
            <el-input v-model="form.authCode" type="password" placeholder="请输入授权码" show-password />
          </el-form-item>
          <el-form-item label="端口" prop="port">
            <template #label>
              <el-popover placement="top-start" effect="dark" trigger="hover" content="此端口是连接发送邮箱服务器的端口，只有寄件邮箱需要填写">
                <template #reference>
                  <el-icon style="display: inline-block;line-height: 36px; height: 36px;">
                    <QuestionFilled />
                  </el-icon>
                </template>
              </el-popover>
              <div>端口</div>
            </template>
            <el-input v-model="form.port" placeholder="请输入端口" />
          </el-form-item>
          <el-form-item label="发送协议" prop="protocol">
            <template #label>
              <el-popover placement="top-start" effect="dark" trigger="hover" content="此为寄件使用协议，只有寄件邮箱需要填写">
                <template #reference>
                  <el-icon style="display: inline-block;line-height: 36px; height: 36px;">
                    <QuestionFilled />
                  </el-icon>
                </template>
              </el-popover>
              <div>发送协议</div>
            </template>
            <el-input v-model="form.protocol" placeholder="请输入发送协议" />
          </el-form-item>
          <el-form-item label="协议服务地址" prop="host">
            <template #label>
              <el-popover placement="top-start" effect="dark" trigger="hover" content="此为寄件使用服务地址，只有寄件邮箱需要填写">
                <template #reference>
                  <el-icon style="display: inline-block;line-height: 36px; height: 36px;">
                    <QuestionFilled />
                  </el-icon>
                </template>
              </el-popover>
              <div>协议服务地址</div>
            </template>
            <el-input v-model="form.host" placeholder="请输入协议服务地址" />
          </el-form-item>
          <el-form-item label="是否使用ssl" prop="ssl">
            <template #label>
              <el-popover placement="top-start" effect="dark" trigger="hover" content="此为是否使用ssl协议，只有寄件邮箱需要填写">
                <template #reference>
                  <el-icon style="display: inline-block;line-height: 36px; height: 36px;">
                    <QuestionFilled />
                  </el-icon>
                </template>
              </el-popover>
              <div>是否使用ssl</div>
            </template>
            <el-select v-model="form.isSsl" placeholder="请选择" clearable style="width: 100%;">
              <el-option v-for="dict in confirmOptions" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model.trim="form.remark" type="textarea" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" icon="Check" @click="handleSave">确 定</el-button>
        <el-button icon="Close" @click="handleCancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import {
  listEmail,
  delEmail,
  getEmail,
  updateEmail,
  addEmail,
} from "@/api/business/email";
import { listInfo } from "@/api/business/tenant";
const { proxy } = getCurrentInstance();
/** 员工管理变量 */
const userList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
/** 员工信息弹窗变量 */
const contractCompanyList = ref([]);
const open = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const roleOptions = ref([]);
const usageCompanyList = ref([]);
const emailType = ref([
  { label: '寄件邮箱', value: 0 },
  { label: '收件邮箱', value: 1 }
])
const confirmOptions = ref([
  { label: '是', value: 1 },
  { label: '否', value: 0 }
])
/** 查询对象 */
const data = reactive({
  form: {
    usageCompanyId: null,
    contractCompanyId: null,
    contractCompanyName: null,
    usageusageCompanyName: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: "",
    nickName: "",
    phoneNumber: "",
    // status: 0,
    deptName: "",
  },
  rules: {
  },
});

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

/** 查询用户列表 */
function getList() {
  loading.value = true;
  listInfo().then((res) => {
    if (res.code == 200) {
      contractCompanyList.value = res.data;
      usageCompanyList.value = res.data;
    }
  });
  listEmail(queryParams.value).then((response) => {
    // for(let i = 0; i < response.rows.length; i++) {
    //   for(let j = 0;j<contractCompanyList.value.length;j++) {
    //     if(response.rows[i].tenantId == contractCompanyList.value[j].value) {
    //       response.rows[i].tenantName = contractCompanyList.value[j].label;
    //     }
    //   }

    // }
    userList.value = response.rows;
    console.log(userList.value)
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQueryUser() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQueryUser();
}
/** 删除按钮操作 */
function handleDeleteUser(id) {
  console.log(ids.value);
  if (id) {
    proxy.$modal
      .confirm("是否确认删除？")
      .then(function () {
        return delEmail(id);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => { });
  }
}
/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
//使用单位更改
function handleChangeUsageCompany() {
  form.value.tenantId = form.value.usageCompanyId;
  for (let i = 0; i < usageCompanyList.value.length; i++) {
    if (form.value.usageCompanyId == usageCompanyList.value[i].value) {
      form.value.usageCompanyName = usageCompanyList.value[i].label;
    }
  }
}
//合同单位更改
function handleChangeContractCompany() {
  console.log(form.value.contractCompanyName)
  console.log(contractCompanyList.value)
  for (let i = 0; i < contractCompanyList.value.length; i++) {
    if (form.value.contractCompanyId == contractCompanyList.value[i].value) {
      form.value.contractCompanyName = contractCompanyList.value[i].label;
    }
  }
}

/**多选删除按钮操作 */
function handleDeleteMultipleUser() {
  if (ids.value) {
    proxy.$modal
      .confirm("是否确认删除？")
      .then(function () {
        return delEmail(ids.value);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => { });
  }
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userName: "",
    nickName: "",
    password: "",
    phoneNumber: "",
    email: "",
    sex: "男",
    remark: "",
    contractCompanyId: null,
    status: "0",
    roleIds: [],
  };
  proxy.resetForm("userRef");
}
/** 取消按钮 */
function handleCancel() {
  open.value = false;
  reset();
}
/** 修改/添加按钮操作 */
function handleShowUserDialog(id) {
  reset();
  if (id) {
    getEmail(id).then((response) => {
      if (response.data.usageCompanyId == "0") {
        response.data.usageCompanyId = null
        response.data.usageCompanyName = null
      }
      response.data.status = response.data.status + ""
      form.value = response.data;
      form.value.roleIds = response.roleIds;
      roleOptions.value = response.roles;
      console.log('response', response)
      form.password = "";
    });
  } else {
    getEmail('0').then((response) => {
      roleOptions.value = response.roles;
      console.log('response', response)
    });
  }
  open.value = true;
}

/** 提交按钮 */
function handleSave() {
  proxy.$refs["userRef"].validate(async (valid) => {
    if (valid) {
      console.log(form.value);
      // 邮箱地址必填
      if (form.value.emailAddress == null || form.value.emailAddress == '') {
        proxy.$modal.msgError("请填写邮箱地址");
        return
      }
      // 判断是否是寄件邮箱 假设是寄件邮箱则寄件邮箱的必填项 需要填满
      if (form.value.type === 0) {
        // 判断是否填写授权码
        if (form.value.authCode == null || form.value.authCode == '') {
          proxy.$modal.msgError("请填写授权码");
          return
        }
        // 判断是否填写端口
        if (form.value.port == null || form.value.port == '') {
          proxy.$modal.msgError("请填写端口");
          return
        }
        // 判断是否填写发送协议
        if (form.value.protocol == null || form.value.protocol == '') {
          proxy.$modal.msgError("请填写发送协议");
          return
        }
        // 判断是否填写协议服务器地址
        if (form.value.host == null || form.value.host == '') {
          proxy.$modal.msgError("请填写协议服务地址");
          return
        }
        // 假设已经有寄件邮箱则弹窗询问是否弃用前邮箱。
        const res = await isExistEmail()
        if (!res) {
          return
        }
      }
      if (form.value.id != undefined) {
        updateEmail(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addEmail(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
// 判断是否已有寄件地址
async function isExistEmail() {
  const query = { type: 0, isStop: 0 }
  const res = await listEmail(query)
  if (res.code == 200 && res.rows.filter(e => e.id != form.value.id).length > 0) {
    return await proxy.$modal
      .confirm("已有寄件邮箱，确认替换？").then(_ => true).catch(_ => false)
  } else {
    return true
  }
}

getList();
</script>
