<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      
      <el-form-item label="投诉分类" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入投诉分类"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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="['his:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:template:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      height="500" 
      border
      v-loading="loading"
      :data="templateList"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="ID" align="left" prop="id" />
      <el-table-column label="投诉分类" align="left" prop="name" />
      <el-table-column label="排序" sortable align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="isLeafNode(scope.row)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDesc(scope.row)"
            v-hasPermi="['his:template:edit']"
          >填写字段</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['his:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['his:template:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级" prop="parentId">
          <treeselect 
            v-model="form.parentId" 
            :options="categoryOptions" 
            :show-count="true" 
            :normalizer="normalizer" 
            :disable-branch-nodes="false"
            :searchable="true"
            :clearable="true"
            placeholder="请选择上级分类" 
          />
        </el-form-item>
        <el-form-item label="投诉分类" prop="name">
          <el-input v-model="form.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择填写字段" :visible.sync="descOpen" width="600px" append-to-body>
      <!-- 添加表头说明 -->
      <div class="field-header">
        <div class="field-name-header">字段名称</div>
        <div class="field-required-header">是否必填</div>
      </div>
      
      <el-checkbox-group v-model="descForm">
        <div v-for="(item, index) in fields" :key="index" class="field-item">
          <div class="field-checkbox-wrapper">
            <el-checkbox :label="item.label" name="desc" v-model="item.checked"></el-checkbox>
          </div>
          <div class="field-switch-wrapper">
            <el-switch
              v-model="item.isRequire"
              active-value="1"
              inactive-value="0"
              :disabled="!item.checked"
              class="require-switch"
            ></el-switch>
          </div>
        </div>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDescForm">确 定</el-button>
        <el-button @click="descCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { treeListTemplate, listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate, exportTemplate } from "@/api/his/complaint";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Template",
  components: {
    Treeselect
  },
  data() {
    return {
      descId: null,
      fields: [
        { label: "详细内容", checked: false, isRequire: 0, desc: "content",type:"文本框" },
        { label: "联系方式", checked: false, isRequire: 0, desc: "phone",type:"文本框"},
        { label: "上传图片", checked: false, isRequire: 0, desc: "urls",type:"图片" },
        { label: "交易截图", checked: false, isRequire: 0, desc: "tradeImage",type:"图片" },
        { label: "被投诉人账号信息", checked: false, isRequire: 0, desc: "account",type:"文本框" },
      ],
      descOpen: false,
      categoryOptions: [],
      loading: true,
      exportLoading: false,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      templateList: [],
      title: "",
      open: false,
      queryParams: {
        name: null,
        isDel: null
      },
      form: {},
      rules: {
        parentId: [
          { required: true, message: "上级编码不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "同级下排序不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "投诉分类不能为空", trigger: "blur" }
        ],
      }
    };
  },
  computed: {
    descForm: {
      get() {
        return this.fields.filter(item => item.checked).map(item => item.label);
      },
      set(value) {
        this.fields.forEach(item => {
          item.checked = value.includes(item.label);
        });
      },
    },
  },
  created() {
    this.getList();
  },
  methods: {
    /**
     * 判断是否为叶子节点（最后一级）
     */
    isLeafNode(row) {
      return !row.children || row.children.length === 0;
    },

    submitDescForm() {
      const result = this.fields
        .filter(item => item.checked)
        .map(item => ({
          name: item.label,
          isRequire: item.isRequire,
          desc: item.desc,
          type: item.type,
        }));
      console.log("提交的数据：", result);
      const param = { id: this.descId, description: JSON.stringify(result) }
      updateTemplate(param).then(response => {
        this.msgSuccess("修改成功");
        this.descOpen = false;
        this.getList();
      });
    },
    
    /** 转换标签数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeListTemplate().then(response => {
        const rootOption = { id: 0, name: '根目录', children: response.data || [] };
        this.categoryOptions = [rootOption];
      });
    },
    
    /** 查询投诉模板列表 */
    getList() {
      this.loading = true;
      treeListTemplate(this.queryParams).then(response => {
        this.templateList = response.data;
        this.total = response.data.length;
        this.loading = false;
      });
    },
    
    cancel() {
      this.open = false;
      this.reset();
    },
    
    descCancel() {
      this.descOpen = false;
      this.descReset();
    },
    
    descReset() {
      this.descForm = [];
    },
    
    reset() {
      this.form = {
        id: null,
        parentId: 0,
        sort: null,
        name: null,
        updateTime: null,
        createTime: null,
        isDel: null
      };
      this.resetForm("form");
    },
    
    handleQuery() {
      this.getList();
    },
    
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      this.open = true;
      this.title = "添加投诉模板";
    },
    
    handleDesc(row) {
      if (!this.isLeafNode(row)) {
        this.msgWarning("只有最后一级分类才能配置填写字段");
        return;
      }
      
      this.descOpen = true;
      this.descId = row.id
      if (row.description) {
        const description = JSON.parse(row.description);
        
        this.fields.forEach(field => {
          // 修复：添加 return 语句或者直接使用箭头函数的简写形式
          const found = description.find(item => item.name === field.label);
          
          if (found) {
            field.checked = true;
            field.isRequire = found.isRequire;
          } else {
            field.checked = false;
            field.isRequire = 0;
          }
        });
      } else {
        // 重置所有字段
        this.fields.forEach(field => {
          field.checked = false;
          field.isRequire = 0;
        });
      }
      
      // 添加调试信息，查看最终的 fields 状态
      console.log("最终 fields 状态:", JSON.stringify(this.fields));
    },
    
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const id = row.id || this.ids
      getTemplate(id).then(response => {
        this.form = response.data;
        if (this.form.parentId === null || this.form.parentId === undefined) {
          this.form.parentId = 0;
        }
        this.open = true;
        this.title = "修改投诉模板";
      });
    },
    
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplate(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除投诉模板编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有投诉模板数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportTemplate(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
/* 表头样式 */
.field-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
  font-weight: bold;
  color: #606266;
}

.field-name-header {
  flex: 1;
  text-align: left;
  padding-left: 20px;
}

.field-required-header {
  width: 120px;
  text-align: center;
}

/* 字段项样式 */
.field-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.field-checkbox-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
}

.field-checkbox-wrapper .el-checkbox {
  margin-right: 20px;
}

.field-switch-wrapper {
  width: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.require-switch {
  margin: 0;
}

/* 对话框内容区域样式调整 */
.el-dialog__body {
  padding: 20px;
}
</style>