<template>
  <div class="app-container">
    <el-row :gutter="20">
      <div style="padding: 10px;margin-bottom: 20px;">
        <span style="margin-right: 20px;">锅炉名称：{{useraddtree}}</span>
        <span>监测名称：{{useradddate}}</span>
      </div>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="选择层次">
            <el-select v-model="arrangementid" placeholder="请选择" @change="positionchange">
                <el-option
                  v-for="item in arrangementoption"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
                </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="选择方位">
            <el-select v-model="positionid" placeholder="请选择" @change="pointchange">
                <el-option
                  v-for="item in positionoption"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
                </el-option>
              </el-select>
          </el-form-item>
        </el-form>

        <div style="display: flex;flex-wrap: wrap;">
          <div v-for="(item,index) in Pointlist" :key="index" style="text-align: center;margin: 20px;position: relative;">
             <el-image
                v-if="item.fileInfos.length!=0"
                style="width: 200px; height: 200px"
                :src="imageurl + item.fileInfos[0].filePath"
                :preview-src-list="prevlist(item.fileInfos)">
              </el-image>
              <img v-else style="width: 200px; height: 200px;padding: 20px;" src="../../../assets/images/notimg.png" />
              <img v-if="item.marks.length!=0" src="../../../assets/images/warring.png" style="position: absolute;width: 30px;height: 30px;left: 0px;top: 0px;"/>
              <div style="background-color: #0080FF;color: white;border-radius: 20px;width: 20px;height: 20px;line-height: 20px;font-size: 15px;position: absolute;right: 0px;top: 0px;">{{item.fileInfos.length}}</div>
              <div>{{item.deptName}}</div>
              <div style="display: flex;justify-content: space-between;">
                <!-- <div @click="upload.open = true">上传</div> -->
                 <el-button type="primary" plain @click="userupload(item.id)">上传</el-button>
                <el-button type="primary" plain @click="compare(item)">比较</el-button>
                <el-button type="primary" plain @click="userremark(item)">标记</el-button>
              </div>
          </div>
        </div>


      </el-col>
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            :render-content="renderContent"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="30%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测人员" prop="createBy">
              <el-input v-model="form.createBy" placeholder="请输入人员姓名" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测日期">
              <el-date-picker
                   v-model="form.overhaulTime"
                   type="date"
                   value-format="yyyy-MM-dd"
                   placeholder="选择检测日期">
                 </el-date-picker>
            </el-form-item>
          </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="remarktype" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
       <el-row>
          <el-col :span="24">
            <el-form-item label="损伤标记描述">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="subremark">确 定</el-button>
        <el-button @click="remarkcancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 比较 -->
    <el-dialog title="比较" :visible.sync="comparetype" width="60%" append-to-body :close-on-click-modal="false">
        <div style="display: flex;justify-content: space-between;">
          <div style="width: 50%;">
            <div>
              <span>当前日期：{{useradddate}}</span>
            </div>
            <el-image
               v-if="comparelist.length!=0"
               v-for="(item,index) in comparelist"
               style="width: 300px; height: 300px;margin: 20px;"
               :src="imageurl + item.filePath"
               :preview-src-list="prevlist(comparelist)">
             </el-image>
          </div>
          <div style="width: 50%;">
            <div>
              <span>历史检测：</span>
              <el-select v-model="compareoverid" placeholder="请选择比较日期" @change="comparechange">
                  <el-option
                    v-for="item in compareoverhaullist"
                    :key="item.id"
                    :label="item.overhaulTime"
                    :value="item.id">
                  </el-option>
                </el-select>
            </div>
                <el-image
                   v-if="historycomparelist.length!=0"
                   v-for="(item,index) in historycomparelist"
                   style="width: 300px; height: 300px;margin: 20px;"
                   :src="imageurl + item.filePath"
                   :preview-src-list="prevlist(historycomparelist)">
                 </el-image>
          </div>
        </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="comparetype = false">确 定</el-button>
      </div>
    </el-dialog>





    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".jpg, .png"
        :headers="upload.headers"
        :action="upload.url + '?overhaulId=' + overid +'&deptId=' + Pointid"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, exportUser, resetUserPwd, changeUserStatus, importTemplate } from "@/api/system/user";
import { addMark,updateMark,compared } from "@/api/system/mark"
import { getToken } from "@/utils/auth";
import { treeselect,treeselectone,addoverhaul,treegetPoint } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      newdef:'../../../assets/images/notimg.png',
      imageurl:process.env.VUE_APP_BASE_API,
      treelist:[],
      useradddate:'',
      useraddtree:'',
      remarktype:false,
      comparetype:false,
      //比较检修记录列表
      compareoverhaullist:[],
      //历史检修列表
      historycomparelist:[],
      comparelist:[],
      //比较检修日期
      compareoverid:'',
      options:[],
      //标记列表
      marks:[],
      //点位id
      Pointid:'',
      //检修记录id
      overid:'',
      //层级列表
      arrangementoption:[],
      //层级下表
      arrangementindex:0,
      //选中层级id
      arrangementid:'',
      //方位列表
      positionoption:[],
      //方位下表
      positionindex:0,
      //方位id
      positionid:'',
      //点位列表
      Pointlist:[],
      value:'',
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {
        remark:''
      },
      defaultProps: {
        children: "overhauls",
        label: "overhaulTime"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/info/add"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        createBy: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    //获取左侧导航
    this.getTreeselect();
    //获取下拉级联数据
    this.getTree()
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    //查询对比检修点位图片列表
    gethistorylist(){
      compared({
        deptId:this.Pointid,
        overhaulId:this.compareoverid,
      }).then(response => {
        this.historycomparelist =  response.data.fileInfos
        this.$modal.msgSuccess("查询成功");
      });
    },



    compare(e){
      this.compareoverhaullist= []
      this.historycomparelist = []
      this.Pointid = e.id
      this.comparelist = e.fileInfos
      for(let i =0 ;i < this.deptOptions.length;i++){
        if(this.deptOptions[i].deptId == e.ancestors.split(',')[1]){
          this.compareoverhaullist = this.deptOptions[i].overhauls
        }
      }
      this.comparetype = true
    },
    prevlist(e){
      let newlist = []
      if(e.length!=0){
        for(let i =0;i<e.length;i++){
          newlist.push(this.imageurl +  e[i].filePath)
        }
        return newlist
      }
    },
    //层次数据变化
    positionchange(e){
      for(let i = 0;i<this.arrangementoption.length;i++){
        if(e == this.arrangementoption[i].id){
          this.arrangementindex = i
          this.positionoption = this.arrangementoption[i].children
          this.positionid = ''
          if(this.positionoption.length!=0){
            this.positionid = this.positionoption[0].id
          }
        }
      }
      console.log("数据变化",e)
    },
    comparechange(e){
      this.compareoverid = e
      this.gethistorylist()
    },
    pointchange(e){
      this.positionid = e
      this.getList();
    },
    userupload(e){
      this.upload.open = true
      this.Pointid = e
    },
    userremark(e){
      this.Pointid = e.id
      this.marks = e.marks
      if(e.marks.length!=0){
        this.form.remark = e.marks[0].remark
      }
      this.remarktype = true
    },



    //查询点位数据 treegetPoint



    /** 查询用户列表 */
    getList() {
      this.loading = true;
      treegetPoint(this.positionid,this.overid).then(response => {
          this.Pointlist = response.data;
          this.loading = false;
        }
      );
    },

    getTree() {
      treeselect().then(response => {
        this.treelist = response.data;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselectone().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.deptId;
      this.overid  = data.id
      this.useradddate = data.overhaulTime
      console.log("data123",data)
      console.log("treelist",this.treelist)
      //默认选择层次
      for(let i=0;i<this.treelist.length;i++){
       if(data.deptId == this.treelist[i].id){
         this.useraddtree = this.treelist[i].label
         this.arrangementoption = this.treelist[i].children
         if(this.treelist[i].children.length!=0){
           this.arrangementid = this.treelist[i].children[0].id
         }
         break;
       }else{
         this.arrangementid = ''
       }
      }
      //默认选择方位
      if(this.arrangementoption[0].children.length!=0){
        this.positionoption = this.arrangementoption[0].children
        this.positionid = this.arrangementoption[0].children[0].id
      }
      // for(let j = 0;j<this.arrangementoption.length;j++){

      // }
      this.getList();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function() {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    remarkcancel(){
      this.remarktype = false
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        createBy: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      getUser().then(response => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.open = true;
        this.title = "创建检测";
        this.form.password = this.initPassword;
      });
    },
    renderContent(h, {node, data, store}) {
      console.log("node",node)
      if (node.level==1) {
        return (
          <span class="custom-tree-node">
                <span>{node.data.deptName}</span>
                <span>
                  <el-button style={data.type == 36 ? 'display:none' : ''} size="mini" type="text"
                             on-click={() => this.setTicket(data)}>创建检测</el-button>
                </span>
              </span>);
      } else {
        return (
          <span class="custom-tree-node" style="font-size:14px">
                <span>{node.data.overhaulTime + '的检测记录'}</span>
              </span>);
      }
    },
    setTicket(data){
      this.open = true;
      this.title = "创建检测";
      console.log("检修id",data)
      this.form.deptId = data.deptId
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const userId = row.userId || this.ids;
      getUser(userId).then(response => {
        this.form = response.data;
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.form.postIds = response.postIds;
        this.form.roleIds = response.roleIds;
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      }).then(({ value }) => {
          resetUserPwd(row.userId, value).then(response => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        }).catch(() => {});
    },
    /** 分配角色操作 */
    handleAuthRole: function(row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addoverhaul(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getTreeselect()
            });
          }
        }
      });
    },
    subremark: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.marks.length != 0) {
            updateMark({
              remark:this.form.remark,
              id:this.marks[0].id
            }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.remarktype = false
              this.getList();
            });
          } else {
            addMark({
              deptId:this.Pointid,
              overhaulId:this.overid,
              remark:this.form.remark
            }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.remarktype = false
              this.getList();
              this.getTreeselect()
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function() {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有用户数据项？').then(() => {
        this.exportLoading = true;
        return exportUser(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.$download.name(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
      this.getList()
    }
  }
};
</script>
