<template>
  <div class="app-container">
    <h2>{{ taskName }}指标体系</h2>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="任务ID" prop="taskId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.taskId"-->
      <!--          placeholder="请输入任务ID"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="字段名称" prop="fieldName">
        <el-input
          v-model="queryParams.fieldName"
          placeholder="请输入字段名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="父菜单ID" prop="parentId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.parentId"-->
      <!--          placeholder="请输入父菜单ID"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="显示顺序" prop="orderNum">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.orderNum"-->
      <!--          placeholder="请输入显示顺序"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="字段标签" prop="fieldLabel">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.fieldLabel"-->
      <!--          placeholder="请输入字段标签"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="默认值" prop="defaultVal">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.defaultVal"-->
      <!--          placeholder="请输入默认值"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="最大值" prop="maxVal">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.maxVal"-->
      <!--          placeholder="请输入最大值"-->
      <!--          clearable-->
      <!--          @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="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ggpx:TaskBase:add']"
        >新增指标
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          v-if="TaskBaseList.length===0"-->
      <!--          @click="handleSelectTemplate"-->
      <!--          v-hasPermi="['ggpx:TaskBase:add']"-->
      <!--        >使用模板-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleClose"
        >关闭
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="TaskBaseList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <!--      <el-table-column label="任务ID" prop="taskId"/>-->
      <el-table-column label="字段名称" align="center" prop="fieldName" min-width="120"/>
      <!--      <el-table-column label="父菜单ID" align="center" prop="parentId"/>-->
      <!--      <el-table-column label="显示顺序" align="center" prop="orderNum"/>-->
      <el-table-column label="字段类型" align="center" prop="fieldType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ggpx_field_type" :value="scope.row.fieldType"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="字段标签" align="center" prop="fieldLabel"/>-->
      <!--      <el-table-column label="默认值" align="center" prop="defaultVal"/>-->
      <el-table-column label="最大值" align="center" prop="maxVal"/>
      <el-table-column label="记录总分" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.fieldType==='number' && scope.row.status === 0" type="success">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <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="['ggpx:TaskBase:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            :disabled="scope.row.parentId!==0"
            v-hasPermi="['ggpx:TaskBase:add']"
          >新增
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ggpx:TaskBase:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改任务基准对话框 -->
    <el-dialog :title="title" :visible.sync="open" fullscreen append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--        <el-form-item label="任务ID" prop="taskId">-->
        <!--          <el-input v-model="form.taskId" placeholder="请输入任务ID"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="字段名称" prop="fieldName">
          <el-input v-model="form.fieldName" placeholder="请输入字段名称"/>
        </el-form-item>
        <el-form-item label="父级字段" prop="parentId">
          <treeselect v-model="form.parentId" :options="TaskBaseOptions" :normalizer="normalizer"
                      placeholder="请选择父级字段"/>
        </el-form-item>
        <!--        <el-form-item label="显示顺序" prop="orderNum">-->
        <!--          <el-input-number v-model="form.orderNum" controls-position="right" :min="0" :max="999"></el-input-number>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="字段标签" prop="fieldLabel" v-if="form.parentId !== 0">-->
        <!--          <el-input v-model="form.fieldLabel" placeholder="请输入字段标签"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="字段类型" prop="fieldType">
          <el-radio-group v-model="form.fieldType">
            <el-radio
              v-for="dict in dict.type.ggpx_field_type"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>

        </el-form-item>
        <!--        <el-form-item label="默认值" prop="defaultVal" v-if="form.fieldType === 'number'">-->
        <!--          <el-input v-model="form.defaultVal" placeholder="请输入默认值"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="最大值" prop="maxVal" v-if="form.fieldType === 'number'">
          <el-input v-model="form.maxVal" placeholder="请输入最大值"/>
        </el-form-item>
        <el-form-item label="计入总分" prop="maxVal" v-if="form.fieldType === 'number'">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" 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="openTemplate" fullscreen append-to-body>
      <el-form>
        <el-form-item label="模板">
          <el-select v-model="templateId" clearable placeholder="请选择模板" @click.native="getTemplateList">
            <el-option
              v-for="item in templateList"
              :key="item.id"
              :label="item.taskName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div v-if="templateId">
        <h2>模板预览</h2>
        <el-form label-width="80px">
          <!--        <el-form-item label="任务ID" prop="taskId">-->
          <!--          <el-input v-model="form.taskId" placeholder="请输入任务ID"/>-->
          <!--        </el-form-item>-->
          <!--        <el-form-item label="样品名称" prop="sampleName">-->
          <!--          <el-input v-model="form.sampleName" placeholder="请输入样品名称"/>-->
          <!--        </el-form-item>-->
          <!-- 遍历fields,动态创建表单 -->
          <div v-for="(field, index) in templateData" :key="index">
            <div v-if="!field.children">
              <el-divider></el-divider>
              <el-form-item :label="field.fieldName" :prop="field.fieldName">
                <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 8}" v-if="field.fieldType === 'textarea'"
                          v-model="field.value"/>
                <el-input v-if="field.fieldType === 'input'" v-model="field.value"/>
                <el-input-number v-if="field.fieldType === 'number'" v-model="field.value"
                                 :min="0" :max="field.maxVal"/>
                <el-radio-group v-if="field.fieldType === 'radio_sf'" v-model="field.value">
                  <el-radio label="是">是</el-radio>
                  <el-radio label="否">否</el-radio>
                </el-radio-group>
                <el-radio-group v-if="field.fieldType === 'radio_diy'" v-model="field.value">
                  <el-radio v-for="(item,index) in field.remark.split('/')" :label="item">{{ item }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <div v-if="field.children && field.children.length > 0">
              <el-divider></el-divider>
              <h3 style="color: #1c84c6">{{ field.fieldName }}</h3>
              <div v-for="(field, index) in field.children" :key="index">
                <el-form-item :label="field.fieldName" :prop="field.fieldName">
                  <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 8}" v-if="field.fieldType === 'textarea'"
                            v-model="field.value"/>
                  <el-input v-if="field.fieldType === 'input'" v-model="field.value"/>
                  <el-input-number v-if="field.fieldType === 'number'" v-model="field.value" :min="0"
                                   :max="field.maxVal"></el-input-number>
                  <span v-if="field.fieldType === 'number'">满分:{{ field.maxVal }}</span>
                  <el-radio-group v-if="field.fieldType === 'radio_sf'" v-model="field.value">
                    <el-radio label="是">是</el-radio>
                    <el-radio label="否">否</el-radio>
                  </el-radio-group>
                  <el-radio-group v-if="field.fieldType === 'radio_diy'" v-model="field.value">
                    <el-radio v-for="(item,index) in field.remark.split('/')" :label="item">{{ item }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            </div>
          </div>
          <el-divider></el-divider>
          <!--        <el-form-item label="任务数据" prop="data">-->
          <!--          <el-input v-model="form.data" placeholder="请输入任务数据"/>-->
          <!--        </el-form-item>-->
          <el-form-item label="组长" prop="groupLeader">
            <el-radio-group v-model="form.groupLeader">
              <el-radio label="是">是</el-radio>
              <el-radio label="否">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <!--        <el-form-item label="备注" prop="remark">-->
          <!--          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>-->
          <!--        </el-form-item>-->
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTemplateForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTaskBase,
  getTaskBase,
  delTaskBase,
  addTaskBase,
  updateTaskBase,
  addTaskBaseBatch
} from "@/api/ggpx/TaskBase";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listTaskList} from "@/api/ggpx/TaskList";

export default {
  name: "TaskBase",
  dicts: ['ggpx_field_type'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: false,
      // 任务基准表格数据
      TaskBaseList: [],
      // 任务基准树选项
      TaskBaseOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openTemplate: false,
      templateId: null,
      templateData: [],
      templateList: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      taskName: this.$route.query.taskName,
      // 查询参数
      queryParams: {
        taskId: null,
        fieldName: null,
        parentId: null,
        orderNum: null,
        fieldType: null,
        fieldLabel: null,
        defaultVal: null,
        maxVal: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskId: [
          {required: true, message: "任务ID不能为空", trigger: "blur"}
        ],
      }
    };
  },
  watch: {
    templateId: {
      handler: function (val) {
        if (val) {
          listTaskBase({taskId: val}).then(response => {
            console.log("watch templateId", response.data);
            this.templateData = this.handleTree(response.data, "id", "parentId");
          });
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询任务基准列表 */
    getList() {
      this.loading = true;

      this.queryParams.taskId = this.$route.params.taskId;
      this.form.taskId = this.$route.params.taskId;

      listTaskBase(this.queryParams).then(response => {
        this.TaskBaseList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 转换任务基准数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.fieldName,
        children: node.children
      };
    },
    /** 查询任务基准下拉树结构 */
    getTreeselect() {
      this.queryParams.taskId = this.$route.params.taskId;
      listTaskBase(this.queryParams).then(response => {
        this.TaskBaseOptions = [];
        const data = {id: 0, fieldName: '顶级指标', children: []};
        data.children = this.handleTreeLevel1(response.data, "id", "parentId");
        this.TaskBaseOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openTemplate = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskId: this.$route.params.taskId,
        fieldName: null,
        parentId: null,
        orderNum: null,
        fieldType: 'input',
        fieldLabel: null,
        defaultVal: null,
        maxVal: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加指标";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.parentId;
      }
      getTaskBase(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改指标";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTaskBase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTaskBase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除任务基准编号为"' + row.id + '"的数据项？').then(function () {
        return delTaskBase(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleSelectTemplate() {
      this.openTemplate = true;
    }
    ,
    getTemplateList() {
      listTaskList({remark: "是"}).then(response => {
        this.templateList = response.rows;
      });
    },
    submitTemplateForm() {
      let templateForm = []
      this.templateData.forEach(item => {
        templateForm.push({
          id: item.id,
          taskId: this.$route.params.taskId,
          fieldName: item.fieldName,
          parentId: item.parentId,
          orderNum: item.orderNum,
          fieldType: item.fieldType,
          fieldLabel: item.fieldLabel,
          defaultVal: item.defaultVal,
          maxVal: item.maxVal,
          status: item.status,
          remark: item.remark
        });
        if (item.children) {
          item.children.forEach(child => {
            templateForm.push({
              id: child.id,
              taskId: this.$route.params.taskId,
              fieldName: child.fieldName,
              parentId: child.parentId,
              orderNum: child.orderNum,
              fieldType: child.fieldType,
              fieldLabel: child.fieldLabel,
              defaultVal: child.defaultVal,
              maxVal: child.maxVal,
              status: child.status,
              remark: child.remark
            });
          })
        }
      });
      addTaskBaseBatch(templateForm).then(response => {
        this.$modal.msgSuccess("导入成功");
        this.openTemplate = false;
        this.getList();
      });

    },
    /** 返回按钮操作 */
    handleClose() {
      const obj = {path: "/TaskList"};
      this.$tab.closeOpenPage(obj);
    },
  }
};
</script>
