<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 label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </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:testTemp: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="['his:testTemp: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="['his:testTemp:remove']"
        >删除</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:testTemp:export']"
          >导出</el-button>
        </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="testTempList" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="模板编号" align="center" prop="tempCode" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="副标题" align="center" prop="title" />
      <el-table-column label="图片" align="center" prop="img" width="100px">
           <template slot-scope="scope">
                  <el-popover
                    placement="right"
                    title=""
                    trigger="hover">
                    <img slot="reference" :src="scope.row.img" width="70px">
                    <img :src="scope.row.img" style="max-width: 150px;">
                  </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="预计分钟" align="center" prop="time" />
      <el-table-column label="题目数量" align="center" prop="num" />
      <el-table-column label="测试人数" align="center" prop="peopleNum" />
   <!--   <el-table-column label="备注" align="center" prop="remark" /> -->
       <el-table-column label="创建时间" align="center" prop="createTime" width="160"/>
        <el-table-column label="更新时间" align="center" prop="updateTime" width="160"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['his:testTemp:edit']"
          >修改</el-button>
          <el-button
               size="mini"
               type="text"
              @click="updateItem(scope.row)"
          >选项管理
          </el-button>
           <el-button
                size="mini"
                type="text"
                @click="handledetails(scope.row)"
                v-hasPermi="['his:testTemp:edit']"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['his:testTemp:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改测一测模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status"  >
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
                <el-form-item label="副标题" prop="title">
                  <el-input v-model="form.title" placeholder="请输入标题" />
                </el-form-item>

                <el-form-item label="图片" prop="img">
                  <el-upload
                              v-model="form.img"
                              class="avatar-uploader"
                              :action="uploadUrl"
                              :show-file-list="false"
                              :on-success="handleAvatarSuccess"
                              :before-upload="beforeAvatarUpload">
                              <img v-if="form.img" :src="form.img" class="avatar" width="300px">
                              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
                <el-form-item label="预计分钟" prop="time">
                  <el-input-number v-model="form.time" label="测试人数"></el-input-number>
                </el-form-item>
                <el-form-item label="题目数量" prop="num">
                  <el-input-number v-model="form.num" label="题目数量"></el-input-number>
                </el-form-item>
                <el-form-item label="测试人数" prop="peopleNum">
                   <el-input-number v-model="form.peopleNum" label="测试人数"></el-input-number>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                   <el-input-number v-model="form.sort" label="排序"></el-input-number>
                </el-form-item>
                <el-form-item label="测试提醒" prop="msg">
                  <el-input v-model="form.msg" placeholder="请输入标题" type="textarea"/>
                </el-form-item>
                <el-form-item label="描述" prop="descs" >
                  <Editor  ref="myeditor"   @on-text-change="updateText"/>
                </el-form-item>


        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
          <el-row>
             <el-col :span="3"><div style="margin-top: 9px;font-weight: bold;float: right; margin-right: 10px;">项目类型</div></el-col>
            <el-col :span="21">
              <el-table :data="itemTypeJson"   >
              <el-table-column label="类型" prop="itemType" align="center" >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.itemType" ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150px" align="center">
                <template slot-scope="scope" >
                    <el-button @click="addRow" size="mini" type="text" >新增</el-button>
                    <el-button @click="updateRow(scope.row)" size="mini" type="text" >编辑内容</el-button>
                    <el-button @click="deleteRow(scope.$index)"   size="mini" type="text" v-if="itemTypeJson.length>1">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            </el-col>
          </el-row>
      </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="TypeOpen" width="700px" append-to-body>
      <el-form ref="item" :model="item"  label-width="80px">
        <el-form-item label="项目类型" prop="itemType">
          <el-input v-model="item.itemType" placeholder="请输入项目类型" />
        </el-form-item>
        <el-form-item label="分值区间" prop="itemType">
         <el-input-number size="small" v-model="item.min" :max="item.max" ></el-input-number> 到 <el-input-number size="small" v-model="item.max" :min="item.min"></el-input-number>
        </el-form-item>



          <el-row>
             <el-col :span="3"><div style="margin-top: 9px;font-weight: bold;float: right; margin-right: 15px;">项目内容</div></el-col>
            <el-col :span="21">
            <el-table :data="item.item"    :cell-style="{ textAlign: 'center' }"		 :header-cell-style="{textAlign: 'center'}"   >
              <el-table-column label="名称" prop="name" >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.name" ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="内容" prop="value" width="340px">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.value" type="textarea" :rows="5"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100px">
                <template slot-scope="scope">
                   <el-button @click="deleteType(scope.$index)"   size="mini" type="text" v-if="item.item.length>1">删除</el-button>
                    <el-button @click="addType" size="mini" type="text" >新增</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="TypeOpen = false">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选项管理" :visible.sync="itemOpen" width="700px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
               <el-col :span="3"><div style="margin-top: 9px;font-weight: bold;float: right; margin-right: 10px;">项目类型</div></el-col>
              <el-col :span="21">
                <el-table :data="itemTypeJson"   >
                <el-table-column label="类型" prop="itemType" align="center" />
                <el-table-column label="操作" width="150px" align="center">
                  <template slot-scope="scope" >
                      <el-button @click="updateitemOpen(scope.row)" size="mini" type="text" >编辑选项</el-button>
                  </template>
                </el-table-column>
              </el-table>
              </el-col>
            </el-row>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="itemOpen = false">确 定</el-button>
      </div>
    </el-dialog>
      <el-dialog title="选项内容管理" :visible.sync="testItemOpen" width="700px" append-to-body>
          <testTempItem  ref="testTempItemDetails" />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="testItemOpen = false">确 定</el-button>
        </div>
      </el-dialog>
       <el-drawer
    	:with-header="false"
            size="75%"
             :title="show.title" :visible.sync="show.open">
         <testTempDetails  ref="Details" />
       </el-drawer>
  </div>
</template>

<script>
import { listTestTemp, getTestTemp, delTestTemp, addTestTemp, updateTestTemp, exportTestTemp } from "@/api/his/testTemp";
import testTempDetails from '../../components/his/testTempDetails.vue';
import testTempItem from '../testTempItem/index.vue';
import Editor from '@/components/Editor/wang';
export default {
  name: "TestTemp",
  components: { testTempDetails ,testTempItem,Editor},
  data() {
    return {
      // 遮罩层
      loading: true,
      show:{
              open:false,
            },

      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      baseUrl: process.env.VUE_APP_BASE_API,
      itemTypeJson: [
        { itemType: "类别1", item: [{ name: "名称",value:"内容"}]},
      ],
      item:[],
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测一测模板表格数据
      testTempList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      itemOpen:false,
      TypeOpen:false,
      testItemOpen:false,
      open: false,
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        analysis: null,
        drugPlan: null,
        foodPlan: null,
        mentalPlan: null,
        livingPlan: null,
        createTime: null,
        upateTime: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],

        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    handleAvatarSuccess(res, file) {
            if(res.code==200){
              this.form.img=res.url;
              self.$forceUpdate()
            }
            else{
              this.msgError(res.msg);
            }
        },
        beforeAvatarUpload(file) {
          const isLt1M = file.size / 1024 / 1024 < 1;
          if (!isLt1M) {
            this.$message.error('上传图片大小不能超过 1MB!');
          }
          return   isLt1M;
        },
    updateText(text){
         this.form.descs=text
       },
    updateitemOpen(row){
      setTimeout(() => {
           this.$refs.testTempItemDetails.getDetails(row.itemType,this.form.tempId);
      }, 1);
      this.testItemOpen=true;
    },
    updateItem(row){

      this.reset();
      getTestTemp(row.tempId).then(response => {
        this.form = response.data;
        this.itemTypeJson=  JSON.parse(this.form.itemTypeJson)
        this.itemOpen=true;
      });
    },


    addRow() {
         this.itemTypeJson.push({ itemType: "类别1", item: [{ name: "名称",value:"内容"}]});
       },
      deleteRow(index) {
        this.itemTypeJson.splice(index, 1);
      },
      addType() {
           this.item.item.push({name: "名称",value:"内容"});
         },
        deleteType(index) {
          this.item.item.splice(index, 1);
        },
      updateRow(row){
        this.item=row;
        this.TypeOpen=true
      },
    /** 查询测一测模板列表 */
    getList() {
      this.loading = true;
      listTestTemp(this.queryParams).then(response => {
        this.testTempList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
        handledetails(row){
            this.show.open=true;
            setTimeout(() => {
                 this.$refs.Details.getDetails(row.tempId);
            }, 1);
        },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tempId: null,
        name: null,
        analysis: null,
        drugPlan: null,
        foodPlan: null,
        mentalPlan: null,
        livingPlan: null,
        createTime: null,
        upateTime: null,
        exercisePlan:null,
        status: 0,
        remark: null,
        itemTypeJson:null,
        tempCode:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.tempId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      setTimeout(() => {
                this.$refs.myeditor.setText("");
              }, 500);
      this.itemTypeJson= [
        { itemType: "类别1", item: [{ name: "名称",value:"内容"}]},
      ];
      this.open = true;
      this.title = "添加测一测模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const tempId = row.tempId || this.ids
      getTestTemp(tempId).then(response => {
        this.form = response.data;
        this.itemTypeJson=  JSON.parse(this.form.itemTypeJson)
        this.open = true;
        this.title = "修改测一测模板";
        setTimeout(() => {
                  if(this.form.descs==null){
                    this.$refs.myeditor.setText("");
                  }
                  else{
                    this.$refs.myeditor.setText(this.form.descs);
                  }
                }, 1);
      });
    },
    hasDuplicateItemType(arr) {
      const itemTypes = new Set();
      for (const obj of arr) {
        if (itemTypes.has(obj.itemType)) {
          return true;
        }
        itemTypes.add(obj.itemType);
      }
      return false;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
            for (var i = 0; i < this.itemTypeJson.length; i++) {
              if (!this.itemTypeJson[i].itemType) {
                this.$message("类型不能为空")
                return;
              }
            }
            if(this.hasDuplicateItemType(this.itemTypeJson)){
              this.$message("类型名称重复");
              return;
            }
            this.form.itemTypeJson=JSON.stringify(this.itemTypeJson )
          if (this.form.tempId != null) {
            updateTestTemp(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTestTemp(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const tempIds = row.tempId || this.ids;
      this.$confirm('是否确认删除测一测模板编号为"' + tempIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTestTemp(tempIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有测一测模板数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportTestTemp(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style>
  .el-table .el-table__header th {
    height: 10px; /* 设置你想要的高度 */
  }
  .avatar-uploader .el-upload {
       border: 1px dashed #d9d9d9;
       border-radius: 6px;
       cursor: pointer;
       position: relative;
       overflow: hidden;
     }
     .avatar-uploader .el-upload:hover {
       border-color: #409EFF;
     }

     .avatar-uploader-icon {
       font-size: 28px;
       color: #8c939d;
       width: 150px;
       height: 150px;
       line-height: 150px;
       text-align: center;
     }
</style>
