<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="提醒事项" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入提醒事项"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮件模板" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入邮件模板"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          v-no-more-click
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索
        </el-button>
        <el-button
          v-no-more-click
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-no-more-click
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iscs:notify:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-no-more-click
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iscs:notify:remove']"
          >批量删除
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="templatesNotifyList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="提醒事项"  prop="name"  ></el-table-column>
      <el-table-column label="是否激活"  prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="1"
            inactive-value="0"
            @change="handleFrozenChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="templateName" label="邮件模板"></el-table-column>
      <el-table-column prop="reminderTime" label="提醒时长">
        <template slot-scope="scope">
          {{formattedTime(scope.row.reminderTime)}}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iscs:notify:edit']"
            >修改
          </el-button>
          <el-button
            v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iscs:notify:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
    <!-- 新增或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="提醒事项" prop="name">
          <el-input v-model="form.name" placeholder="请输入提醒事项" />
        </el-form-item>
        <el-form-item label="邮件模板" prop="templateCode">
         <el-select v-model="form.templateCode">
           <el-option v-for="item in templatesList" :key="item.templateCode" :label="item.templateName" :value="item.templateCode" >
           </el-option>
         </el-select>
        </el-form-item>
        <el-form-item label="提醒时长" prop="reminderTime">
          <div class="time-picker">
            <div
              class="time-unit"
              v-for="(unit, index) in timeUnits"
              :key="index"
            >
              <select
                v-model="timeValues.reminderTime[unit.name]"
                :id="unit.name"
              >
                <option
                  v-for="option in unit.options"
                  :key="option"
                  :value="option"
                >
                  {{ option }}
                </option>
              </select>
              <label :for="unit.name">{{ unit.label }}</label>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button v-no-more-click @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listIsMailNotifyConfigPage,
  addIsMailNotifyConfig,
  deleteIsMailNotifyConfig,
  updateIsMailNotifyConfig,
  getIsMailNotifyConfigById,
} from "@/api/mes/email/notify";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { genCode } from "@/api/system/autocode/rule";
import Template from "@/views/print/printtemplate/list.vue";
import { listEmailTemplates } from '@/api/mes/email/templates'
import { changeFrozenState } from '@/api/mes/wm/location'

export default {
  name: "Dept",
  dicts: ["sys_normal_disable", "sop_type"],
  components: { Template, Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      //自动生成编码
      autoGenFlag: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 选中数组
      codes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 邮件模板列表
      templatesList: [],//模板列表
      templatesNotifyList:[],//提醒列表
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: "",
        templateName: "",
      },
      isEdit: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateCode: [
          { required: true, message: "邮件模板编号不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "邮件模板名称不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "邮件模板内容不能为空", trigger: "blur" },
        ],
      },
      timeUnits: [
        {
          name: "days",
          label: "天",
          options: Array.from({ length: 31 }, (_, i) => i),
        },
        {
          name: "hours",
          label: "小时",
          options: Array.from({ length: 24 }, (_, i) => i),
        },
        {
          name: "minutes",
          label: "分钟",
          options: Array.from({ length: 60 }, (_, i) => i),
        },
        {
          name: "seconds",
          label: "秒",
          options: Array.from({ length: 60 }, (_, i) => i),
        },
      ],
      // 借用时长
      timeValues: {
        reminderTime: {
          days: 0,
          hours: 0,
          minutes: 0,
          seconds: 0,
        },

      },
    };
  },
  created() {
    this.getList();
    this.getOtherList()
  },

  methods: {
    // 是否激活
    handleFrozenChange(row){
      console.log(row);
      updateIsMailNotifyConfig(row).then(response => {
        console.log(response);
        if(row.status == "0"){
          this.$message.info('取消激活')
        }else if(row.status == "1"){
          this.$message.success('激活成功')
        }

      })
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listIsMailNotifyConfigPage(this.queryParams).then((response) => {
        debugger;
        this.templatesNotifyList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
        console.log(response.data.records, "列表内容");
      });
    },
    getOtherList(){
      const data={
        current: 1,
        size: -1,
      }
      listEmailTemplates(data).then((response) => {
        debugger;
        this.templatesList = response.data.records;
      })
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        templateName: undefined,
      };
      this.autoGenFlag = false;
      // 重置所有时间值
      const resetTimeValues = (timeObj) => {
        timeObj.days = 0;
        timeObj.hours = 0;
        timeObj.minutes = 0;
        timeObj.seconds = 0;
      };

      resetTimeValues(this.timeValues.reminderTime);
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.name = "";
      this.queryParams.templateName = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.codes = selection.map((item) => item.configId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit = false;
      this.title = "新增邮件提醒";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEdit = true;
      getIsMailNotifyConfigById(row.configId).then((response) => {
        this.form = response.data;
        const convertTime = (time) => ({
          days: Math.floor(time / (24 * 60 * 60)),
          hours: Math.floor((time % (24 * 60 * 60)) / (60 * 60)),
          minutes: Math.floor((time % (60 * 60)) / 60),
          seconds: time % 60,
        });

        this.timeValues.reminderTime = convertTime(response.data.reminderTime);
        this.open = true;
        this.title = "修改邮件提醒";
      });
    },
    // 时间转换
    formattedTime(totalSeconds) {
      const days = Math.floor(totalSeconds / (24 * 60 * 60));
      const hours = Math.floor((totalSeconds % (24 * 60 * 60)) / (60 * 60));
      const minutes = Math.floor((totalSeconds % (60 * 60)) / 60);
      const seconds = totalSeconds % 60;

      const parts = [];
      if (days > 0) parts.push(`${days}天`);
      if (hours > 0) parts.push(`${hours}小时`);
      if (minutes > 0) parts.push(`${minutes}分钟`);
      if (seconds > 0) parts.push(`${seconds}秒`);

      return parts.join(" ");
    },
    /** 提交按钮 */
    submitForm: function () {
      const calculateTotalSeconds = ({ days, hours, minutes, seconds }) =>
        ((days * 24 + hours) * 60 + minutes) * 60 + seconds;

      this.form.reminderTime = calculateTotalSeconds(
        this.timeValues.reminderTime
      );
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            updateIsMailNotifyConfig(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addIsMailNotifyConfig(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateCodes = row.configId || this.codes;
      this.$modal
        .confirm('是否确认删除所选数据项？')
        .then(function () {
          return deleteIsMailNotifyConfig(templateCodes);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.time-picker {
  display: flex;
  gap: 15px;
  align-items: center;
  padding: 0 10px;
  border-radius: 8px;
}

.time-unit {
  /* width: 100%; */
  /* background: #000; */
  display: flex;
  /* flex-direction: column; */
}

label {
  font-size: 14px;
  color: #333;
  margin-left: 10px;
}

select {
  padding: 8px;
  margin-left: -10px;
  font-size: 14px;
  border: 1px solid #ddd;
  border-radius: 4px;
  transition: border-color 0.3s ease;
}

select:focus {
  border-color: #007bff;
  outline: none;
}
</style>
