<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName" v-if="!userStore.currentProId">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板名称" prop="temName">
        <el-input
          v-model="queryParams.temName"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板类型" prop="temType">
        <el-select v-model="queryParams.temType" placeholder="请选择模板类型" clearable>
          <el-option
            v-for="dict in bas_tem_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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-alert
      title="温馨提示"
      type="success"
      description="上传多个相同类型的模板，在生成承诺书文件时，会读取最新且有效的文件，请至少保证一个生效中的模板文件"
      show-icon
      style="margin-bottom: 20px;"
    />

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

    <el-table v-loading="loading" :data="basTemplateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属公司" align="center" prop="comName" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="模板名称" align="center" prop="temName" />
      <el-table-column label="模板类型" align="center" prop="temType" width="150">
        <template #default="scope">
          <dict-tag :options="bas_tem_type" :value="scope.row.temType"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="修改时间" align="center" prop="updateTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="isDel" width="100">
        <template #default="scope">
          <el-tooltip :content="scope.row.isDel == 0 ? '启用' : '停用'" placement="top">
            <el-switch
              :active-value="parseInt(0)"
              :inactive-value="parseInt(1)"
              v-model="scope.row.isDel"
              @change="setStatus($event, scope.row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="预览模板" align="center" prop="temPath" width="120">
        <template #default="scope">
          <el-button link type="primary" icon="Position" @click="handlePreview(scope.row)" v-hasPermi="['manage:basTemplate:query']">预览模板</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="120" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:basTemplate:edit']">修改</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-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="basTemplateRef" :model="form" :rules="rules" label-width="88px">
        <el-alert
          title="温馨提示"
          type="warning"
          description="业务模板是劳务人员签署进场文件时的模板，文件中有 [关键字] 埋点，修改时请联系运维人员。"
          show-icon
          style="margin-bottom: 20px;"
        />
        <el-form-item label="项目名称" v-if="form.projectId">
          <el-tag effect="plain">{{ form.projectName }}</el-tag>
        </el-form-item>
        <el-form-item label="模板名称" prop="temName">
          <el-input v-model="form.temName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板类型" prop="temType">
          <el-select v-model="form.temType" placeholder="请选择模板类型" style="width:100%">
          <el-option
            v-for="dict in bas_tem_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        </el-form-item>
        <el-form-item label="模板文件" prop="temPath">
          <file-upload v-model="form.temPath" :limit="1" :fileType="['docx']" :fileSize="50" />
        </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="BasTemplate">
import { listBasTemplate, getBasTemplate, delBasTemplate, addBasTemplate, updateBasTemplate, previewBasTemplate } from "@/api/manage/basTemplate";
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance();
const { sys_is_del, bas_tem_type} = proxy.useDict('sys_is_del', 'bas_tem_type');

const userStore = useUserStore()
const basTemplateList = 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 data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    comId: null,
    projectId: null,
    projectName: null,
    temName: null,
    temType: null,
    isDel: null,
  },
  rules: {
    temName: [{ required: true, message: "模板名称不能为空", trigger: "blur" }],
    temType: [{ required: true, message: "模板类型不能为空", trigger: "blur" }],
    temPath: [{ required: true, message: "模板文件不能为空", trigger: "change" }],
  }
});

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

/** 查询业务模板管理列表 */
function getList() {
  loading.value = true;
  listBasTemplate(queryParams.value).then(response => {
    basTemplateList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    comId: null,
    projectId: null,
    temName: null,
    temType: null,
    temPath: null,
    isDel: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("basTemplateRef");
}

/** 搜索按钮操作 */
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() {
  if(!userStore.currentProId){
    proxy.$modal.msgWarning("请切换到项目数据！！！");
    return false;
  }
  reset();
  form.value.comId = userStore.currentComId;
  form.value.comName = userStore.currentComName;
  form.value.projectId = userStore.currentProId;
  form.value.projectName = userStore.currentProName;
  open.value = true;
  title.value = "添加业务模板";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getBasTemplate(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改业务模板";
  });
}

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

/** 启用状态滑块控制 */
function setStatus(val, row) {
  proxy.$modal
    .confirm(`是否确认${val == 0 ? "启用" : "停用"}当前数据项？`)
    .then(function () {
      let param = {'id': row.id, 'isDel': val};
      return updateBasTemplate(param);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("修改成功");
    })
    .catch(() => {
      // 取消时恢复原始开关状态
      if (val == 0) {
        row.isDel = 1;
      } else {
        row.isDel = 0;
      }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除业务模板管理编号为"' + _ids + '"的数据项？').then(function() {
    return delBasTemplate(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/basTemplate/export', {
    ...queryParams.value
  }, `basTemplate_${new Date().getTime()}.xlsx`)
}

/** 模板预览 */
function handlePreview(row){
  previewBasTemplate(row.id).then(res=>{
    if(res.code==200){
      proxy.$download.resource(res.msg);
    }
  });
}

getList();
</script>
