<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 创建单位 -->
      <el-form-item label="创建单位" prop="createByBranch">
        <el-input
          v-model="queryParams.createByBranch"
          placeholder="请输入创建单位"
          clearable
        />
      </el-form-item>
      <!-- 创建部门 -->
      <el-form-item label="创建部门" prop="createByDeptName">
        <el-input
          v-model="queryParams.createByDeptName"
          placeholder="请输入创建部门"
          clearable
        />
      </el-form-item>
      <!-- 创建人 -->
      <el-form-item label="创建人" prop="createByUserName">
        <el-input
          v-model="queryParams.createByUserName"
          placeholder="请输入创建人"
          clearable
        />
      </el-form-item>
      <!-- 创建时间 -->
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" value-format="yyyy-MM-dd" type="daterange" placeholder="选择日期"
                        @change="dateRangeChange" style="width: 220px;" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <!-- 模版名称 -->
      <el-form-item label="模版名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模版名称"
          clearable
        />
      </el-form-item>
      <!-- 任务类型 -->
      <el-form-item label="任务类型" prop="taskType">
        <el-select
          v-model="queryParams.taskType"
          placeholder="请选择任务类型"
          clearable
          filterable
        >
          <el-option
            v-for="dict in dict.type.task_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- 任务标签 -->
      <el-form-item label="任务标签" prop="tagNames">
        <el-input
          v-model="queryParams.tagNames"
          placeholder="请输入任务标签"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button 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
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['task:template:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['task:template:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['task:template:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['task:template:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column label="任务类型" align="center" prop="taskType" sortable='custom'>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_type" :value="scope.row.taskType"/>
        </template>
      </el-table-column>
      <el-table-column label="任务标题" align="center" prop="taskTitle" />
      <el-table-column label="任务要求" align="center" >
        <template slot-scope="scope">
          <div v-html="scope.row.taskContent"></div>
        </template>
      </el-table-column>
      <el-table-column label="任务标签" align="center" prop="tagNames" />
      <el-table-column label="创建单位" align="center" prop="createByBranch" />
      <el-table-column label="创建部门" align="center" prop="createByDeptName" />
      <el-table-column label="创建人" align="center" prop="createByUserName" />
      <el-table-column label="创建时间" align="center" prop="createTimeVo" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['task:template:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['task:template:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              <el-select
                v-model="form.taskType"
                placeholder="请选择任务类型"
                :disabled="!isEditMode"
                clearable
                filterable
                style="width: 100%;"
              >
                <el-option
                  v-for="dict in dict.type.task_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="form.templateName" placeholder="请输入模板名称" :disabled="!isEditMode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务标题" prop="taskTitle">
              <el-input v-model="form.taskTitle" placeholder="请输入任务标题" :disabled="!isEditMode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="任务要求">
              <editor v-model="form.taskContent" :min-height="200" :disabled="!isEditMode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" :rows="3" :disabled="!isEditMode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务标签">
          <tag-table
            :tags="form.tags"
            :disabled="!isEditMode"
            :template-id="form.id"
            @update:tags="(newTags) => form.tags = newTags"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="isEditMode">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {pageListTemplate, getTemplate, delTemplate, addTemplate, updateTemplate} from "@/api/task/template";
import { listTag } from "@/api/system/tag";
import TagTable from './components/TagSelector'
import Editor from '@/components/Editor' // 假设存在该组件用于任务要求编辑，需确保引入正确

export default {
  name: "Template",
  components: {
    TagTable,
    Editor
  },
  dicts: ['task_type'], // 添加字典声明
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        createByBranch: null,
        createByDeptName: null,
        createByUserName: null,
        startCreateTime: null,
        endCreateTime: null,
        templateName: null,
        taskTitle: null,
        taskType: null,
        tagNames: null,
        pageNum: 1, // 初始化页码为1
        pageSize: 10 // 初始化每页显示条数为10
      },
      // 表单参数
      form: {
        id: null,
        taskType: null,
        templateName: null,
        taskTitle: null,
        taskContent: null,
        remarks: null,
        tagIds: [],
        tags: []
      },
      // 表单校验
      rules: {
        taskType: [
          {required: true, message: "任务类型不能为空", trigger: "change"}
        ],
        templateName: [
          {required: true, message: "模板名称不能为空", trigger: "blur"}
        ],
        taskTitle: [
          {required: true, message: "任务标题不能为空", trigger: "blur"}
        ],
        taskContent: [
          {required: true, message: "任务要求不能为空", trigger: "blur"}
        ],
      },
      tagList: [],
      dateRange: [],
      isEditMode: false // 用于判断是否是编辑模式
    };
  },
  created() {
    this.getList();
    this.fetchTagList();
  },
  methods: {
    dateRangeChange(val) {
      this.queryParams.startCreateTime = val?.[0];
      this.queryParams.endCreateTime = val?.[1];
    },
    async fetchTagList() {
      try {
        const response = await listTag();
        this.tagList = response.data;
      } catch (error) {
        console.error('获取任务标签列表失败', error);
      }
    },
    /** 查询任务模板列表 */
    getList() {
      this.loading = true;
      pageListTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(e => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskType: null,
        templateName: null,
        taskTitle: null,
        taskContent: null,
        remarks: null,
        tagIds: [],
        tags: []
      };
      this.resetForm("form");
    },
    //排序
    handleSortChange(col) {
      this.$sortBy(col, this.queryParams);
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.names = selection.map(item => item.id);
      this.single = selection.length!== 1;
      this.multiple =!selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务模板";
      this.isEditMode = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTemplate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改任务模板";
        this.isEditMode = true;
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids;
      getTemplate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看任务模板";
        this.isEditMode = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id!= null) {
            const tagIds = this.form.tags.map(tag => tag.id);
            const updatedForm = {
              ...this.form,
              tagIds: tagIds
            };
            updateTemplate(updatedForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const tagIds = this.form.tags.map(tag => tag.id);
            const newForm = {
              ...this.form,
              tagIds: tagIds
            };
            addTemplate(newForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.id || this.names;
      this.$modal.confirm('是否确认删除任务模板为"' + names + '"的数据项？').then(function () {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('task/template/export', {
        ...this.queryParams
      }, `任务模板_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>


<style scoped>
.el-form-item__label {
  width: 120px;
  text-align: right;
  padding-right: 10px;
}
.el-input {
  width: 100%;
}
</style>
