<template>
  <div class="sys-box plan-box">
    <div class="sys-operate">
      <el-button type="primary" @click="back()">{{
        config.cancelText
      }}</el-button>
      <el-button type="primary" @click="tempSave('form')" :disabled="isDisabled"
        >暂存</el-button
      >
      <el-button type="primary" @click="save('form')" :disabled="isDisabled"
        >提交</el-button
      >
    </div>
    <div class="sys-form">
      <el-form
        v-loading="loading"
        label-width="120px"
        :model="formData"
        ref="form"
        :rules="ruleForm"
      >
        <div class="flex">
          <el-form-item label="计划单号" class="form-inline">
            <el-input
              placeholder="计划单号系统自动生成"
              v-model="formData.workOrderNo"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="计划名称"
            prop="name"
            class="form-inline form-line"
          >
            <el-input
              placeholder="请填写计划名称"
              v-model="formData.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="巡检人" prop="engineerName" class="form-inline">
            <!-- <el-input placeholder="请选择巡检人" readonly v-model="formData.engineerName">
              <el-button slot="append" @click="chooseUserVisible = true" icon="el-icon-search"></el-button>
            </el-input> -->
            <btn-input
              :valueText.sync="formData.engineerName"
              :valueId.sync="formData.engineerId"
              :chooseVisible.sync="chooseUserVisible"
            ></btn-input>
          </el-form-item>
          <el-form-item label="巡检部门" class="form-inline">
            <el-input
              placeholder
              v-model="formData.deptName"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="巡检人电话" class="form-inline">
            <el-input v-model="formData.cellphone" disabled></el-input>
          </el-form-item>
          <el-form-item
            label="计划开始时间"
            prop="startTime"
            class="form-inline"
          >
            <el-date-picker
              :picker-options="start_datetime"
              v-model="formData.startTime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              clearable
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="计划结束时间" prop="endTime" class="form-inline">
            <el-date-picker
              :picker-options="end_datetime"
              v-model="formData.endTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              clearable
              format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item
            label="提前"
            prop="expireday"
            class="form-inline form-short"
          >
            <el-input-number
              v-model="formData.expireday"
              placeholder="请填写"
              :min="0"
            ></el-input-number>
            小时提醒
          </el-form-item>
          <el-form-item
            label="巡检间隔时间"
            prop="frequency"
            class="form-inline form-short"
          >
            <el-input-number
              v-model="formData.frequency"
              placeholder="请填写"
              :min="1"
            ></el-input-number>
            小时
          </el-form-item>
          <el-form-item label="巡检超期时间" prop="xjcqsj" class="form-inline">
            <el-input-number
              v-model="formData.xjcqsj"
              placeholder="请填写"
              :min="1"
            ></el-input-number>
            <!-- <el-date-picker
              v-model="formData.xjcqsj"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              clearable
              format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
            ></el-date-picker> -->
          </el-form-item>
        </div>
        <el-form-item label>
          <div class="sys-operate">
            <el-button type="primary" @click="chooseDevicesVisible = true"
              >选择设备</el-button
            >
            <el-button
              type="primary"
              @click="removeDevice()"
              :disabled="btnDelDisabled"
              >删除</el-button
            >
          </div>
          <el-table
            :data="devices"
            :header-cell-style="{
              fontWeight: 'normal',
              textAlign: 'center',
              backgroundColor: '#eceff4',
              color: '#222'
            }"
            border
            @selection-change="handleDeviceChange"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="serialno"
              align="center"
              show-overflow-tooltip
              label="设备编号"
            ></el-table-column>
            <el-table-column
              prop="name"
              align="center"
              show-overflow-tooltip
              label="设备名称"
            ></el-table-column>
            <el-table-column align="center" show-overflow-tooltip label="状态">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.qy"
                  active-text="启用"
                  inactive-text="禁用"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                >
                </el-switch>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label>
          <div class="sys-operate">
            <el-button type="primary" @click="chooseStandardsVisible = true"
              >巡检标准</el-button
            >
            <el-button
              type="primary"
              @click="removeDevices()"
              :disabled="btnDisabled"
              >删除</el-button
            >
          </div>
          <el-table
            :data="proList"
            :header-cell-style="{
              fontWeight: 'normal',
              textAlign: 'center',
              backgroundColor: '#eceff4',
              color: '#222'
            }"
            border
            @selection-change="handleDevicesChange"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="name"
              align="center"
              show-overflow-tooltip
              label="巡检项目"
            ></el-table-column>
            <el-table-column
              prop="function"
              align="center"
              show-overflow-tooltip
              label="巡检标准"
            ></el-table-column>
            <el-table-column
              prop="xjmb"
              align="center"
              show-overflow-tooltip
              label="巡检模板"
            ></el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4 }"
            v-model="formData.content"
            placeholder="备注"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <!--选择设备-->
    <ChooseDevices
      :visible.sync="chooseDevicesVisible"
      @change="getDevice"
      :isPatrolProject="1"
    ></ChooseDevices>
    <!--选择巡检标准-->
    <ChooseStandard
      :visible.sync="chooseStandardsVisible"
      @change="getStandard"
    ></ChooseStandard>
    <!--选择用户-->
    <DialogChooseSingleUser
      :visible.sync="chooseUserVisible"
      @change="getUser"
    ></DialogChooseSingleUser>
  </div>
</template>

<script>
import btnInput from "@/components/btnInput.vue";
import ChooseDevices from "../../../components/System/dialogChooseDevices";
import ChooseStandard from "./components/dialogChooseStandard";
import DialogChooseSingleUser from "@/components/System/dialogChooseSingleUser";
import { mapState, mapActions, mapGetters, mapMutations } from "vuex";
import config from "@/utils/config.js";
export default {
  components: {
    btnInput,
    ChooseDevices,
    ChooseStandard,
    DialogChooseSingleUser
  },
  name: "inspection_plan_add",
  data() {
    return {
      btnDisabled: false,
      formData: {
        engineerId: null,
        engineerName: "",
        deptName: "",
        cellphone: ""
      },
      start_datetime: {
        disabledDate: time => {
          return time.getTime() < Date.now();
        }
      },
      end_datetime: {
        disabledDate: time => {
          return time.getTime() < Date.now();
        }
      },
      ruleForm: {
        engineerName: [
          { required: true, message: "请选择巡检人", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "请选择计划开始时间", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "请选择计划完成时间", trigger: "change" }
        ],
        xjcqsj: [
          { required: true, message: "请选择巡检超期时间", trigger: "change" }
        ],
        name: [
          { required: true, message: "请填写计划名称", trigger: "change" }
        ],
        expireday: [
          { required: true, message: "请填写提醒小时", trigger: "change" }
        ],
        frequency: [
          { required: true, message: "请填写巡检间隔时间", trigger: "change" }
        ]
      },
      chooseUserVisible: false,

      getUserList: [], //用户
      typeList: [], //任务等级
      tableData: [],
      deviceList: [], //设备列表
      deptList: [], //部门集合
      chooseStandardsVisible: false,
      standards: [], //项目
      chooseStandards: [],
      chooseDevicesVisible: false,
      devices: [], //项目
      chooseDevices: [],
      btnDelDisabled: true,
      btnOtherDisabled: true,
      isDisabled: false,
      loading: false,
      arr: [],
      config: config,
      proList: [],
      choosesDevices: []
    };
  },
  mounted() {
    this.initialize();
    if (this.$route.query.id) {
      this.formData.id = this.$route.query.id;
      this.getDetail();
    }
  },
  watch: {
    formData: {
      handler(newVal, oldVal) {
        if (newVal.engineerId == "") {
          this.formData.engineerName = "";
          this.formData.cellphone = "";
          this.formData.deptName = "";
        }
      },
      deep: true
    }
  },
  methods: {
    ...mapMutations({
      removeTagNav: "tagNav/removeTagNav"
    }),
    /**
     * 获取用户
     */
    getUser(data) {
      //console.log(data);
      if (data) {
        this.formData.engineerId = data.id;
        this.formData.engineerName = data.name;
        this.formData.deptName = data.deptName;
        this.formData.cellphone = data.mobile;
      }
    },
    /**
     * 获取明细
     */
    getDetail() {
      this.loading = true;
      this.$api.patroPlanAPI
        .planDetail({ id: this.formData.id })
        .then(res => {
          if (res.code === 0) {
            this.formData = Object.assign({}, this.formData, res.patrolplan);
            this.formData.workOrderNo = res.patrolplan.workOrderNo;
            this.formData.engineerName = res.patrolplan.patrolPersonName;
            this.formData.engineerId = res.patrolplan.patrolPersonId;
            this.formData.deptName = res.patrolplan.patroldeptName;
            this.formData.expireday = res.patrolplan.expireDay;
            this.formData.frequency = res.patrolplan.frequency;
            let devideInfo = res.deviceDOS;
            if (devideInfo && devideInfo.length > 0) {
              devideInfo.map(el => (el.qy = el.qy == 1 ? true : false));
            } else {
              devideInfo = [];
            }
            this.devices = devideInfo;
            this.proList = res.projectDOS;
            // if (res.patrolPlanDetail) {
            //   res.patrolPlanDetail.forEach(p => {
            //     if (p.patrolProject) {
            //       if (p.patrolProject instanceof Array) {
            //         p.patrolProject.forEach(a => {
            //           this.devices.push({
            //             id: p.deviceId,
            //             serialno: p.serialno,
            //             name: p.cdName,
            //             projectname: a.name,
            //             profunc: a.function,
            //             proid: a.id
            //           });
            //         });
            //       } else {
            //         let a = p.patrolProject;
            //         this.devices.push({
            //           id: p.deviceId,
            //           serialno: p.serialno,
            //           name: p.cdName,
            //           projectname: a.name,
            //           profunc: a.function,
            //           proid: a.id
            //         });
            //       }
            //     }
            //   });
            // }
          }
          this.loading = false;
        })
        .catch(r => {
          this.loading = false;
          console.log(r);
        });
    },

    getMyTable() {
      let arr = [];
      let s = 0;
      let table = this.devices;
      let getTable = [];
      table.forEach((item, i, data) => {
        if (arr.length) {
          s = arr[arr.length - 1].row + data[i - 1].standards.length;
        }
        arr.push({
          row: s,
          index: item.standards.length
        });
        if (item.standards && item.standards.length) {
          item.standards.forEach(subItem => {
            getTable.push({
              id: item.id,
              serialno: item.serialno,
              name: item.name,
              projectid: subItem.id,
              projectname: subItem.name,
              profunc: subItem.function
            });
          });
        }
      });
      this.arr = arr;
      this.devices = getTable;
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1 || columnIndex === 2) {
        let obj = [0, 0];
        this.arr.some(v => {
          if (rowIndex === v.row) {
            obj = [v.index, 1];
          }
        });
        return obj;
      }
    },
    /**
     * 获取选择的巡检标准
     */
    getStandard(val) {
      if (val) {
        this.proList = val;
        // let item = this.chooseDevices[0];
        // let standardList = [];
        // var index = this.devices.findIndex(p => {
        //   if (p.proid) {
        //     return false;
        //   } else {
        //     if (item.id == p.id) {
        //       return true;
        //     }
        //   }
        // });
        // if (index !== -1) {
        //   this.devices.splice(index, 1);
        // }
        // val.forEach(p => {
        //   this.devices.push({
        //     id: item.id,
        //     serialno: item.serialno,
        //     name: item.name,
        //     projectname: p.name,
        //     profunc: p.function,
        //     proid: p.id
        //   });
        // });
      }
    },
    /**
     * 移除选择的巡检标准
     */
    removeStandard() {
      if (this.chooseStandards) {
        this.chooseStandards.forEach(p => {
          var index = this.standards.findIndex(item => {
            if (item.id == p.id) {
              return true;
            }
          });
          this.standards.splice(index, 1);
        });
      }
    },
    /**
     * 处理选择
     */
    handleStandardChange(val) {
      this.chooseStandards = val;
    },

    /**
     * 获取选择的设备
     */
    getDevice(val) {
      console.log(val);
      if (val) {
        val.forEach(p => {
          if (p.deviceProjectList) {
            for (var i = 0; i < p.deviceProjectList.length; i++) {
              this.devices.push({
                id: p.id,
                serialno: p.serialno,
                name: p.name,
                qy: true,
                projectname: p.deviceProjectList[i].patrolProjectName,
                profunc: p.deviceProjectList[i].patrolProjectFunction,
                proid: p.deviceProjectList[i].patrolProjectId
              });
              // p.projectname= p.deviceProjectList[i].patrolProjectName,
              // p.profunc= p.deviceProjectList[i].patrolProjectFunction,
              // p.proid= p.deviceProjectList[i].id
            }
            // this.devices.push(p);
          } else {
            p.projectname = "";
            p.profunc = "";
            p.qy = true;
            this.devices.push(p);
          }
        });
        let result = this.devices;
        this.devices = JSON.parse(JSON.stringify(result));
        //this.getMyTable();
      }
    },
    /**
     * 移除选择的设备
     */
    removeDevice() {
      if (this.chooseDevices) {
        this.chooseDevices.forEach(p => {
          var index = this.devices.findIndex(item => {
            if (item.id == p.id) {
              return true;
            }
          });
          this.devices.splice(index, 1);
        });
      }
    },
    removeDevices() {
      if (this.choosesDevices) {
        this.choosesDevices.forEach(p => {
          var index = this.proList.findIndex(item => {
            if (p.proid) {
              if (item.id == p.id && item.proid == p.proid) {
                return true;
              }
            } else {
              if (item.id == p.id) {
                return true;
              }
            }
          });
          this.proList.splice(index, 1);
        });
      }
    },
    /**
     * 处理选择
     */
    handleDevicesChange(val) {
      this.choosesDevices = val;
      let isFlag = true;
      let isDelFlag = true;
      if (val.length > 0) {
        isDelFlag = false;
        if (val.length == 1) {
          isFlag = false;
        }
      } else {
        isFlag = true;
        isDelFlag = true;
      }
      this.btnDisabled = isDelFlag;
      this.btnOtherDisabled = isFlag;
    },
    handleDeviceChange(val) {
      this.chooseDevices = val;
      let isFlag = true;
      let isDelFlag = true;
      if (val.length > 0) {
        isDelFlag = false;
        if (val.length == 1) {
          isFlag = false;
        }
      } else {
        isFlag = true;
        isDelFlag = true;
      }
      this.btnDelDisabled = isDelFlag;
      this.btnOtherDisabled = isFlag;
    },
    /**
     * 初始化数据
     */
    initialize() {
      Promise.all([
        this.$api.commonAPI.getUsers(),
        this.$api.commonAPI.getDepts(),
        this.$api.dictAPI.getDictsByType("device_type")
      ])
        .then(([r1, r2, r3]) => {
          if (r1.code === 0) {
            this.getUserList = r1.datas;
          }
          if (r2.code === 0) {
            this.deptList = r2.datas;
          }
          if (r3.code === 0) {
            this.typeList = r3.datas;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    /**
     * 取消方法
     */
    back() {
      this.removeTagNav({
        path: this.$route.path,
        title: this.$route.meta.name
      });
      this.$router.push({ path: "/inspection/plan", query: { t: Date.now() } });
    },
    /**
     * 保存
     */
    save(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const diff =
            new Date(this.formData.endTime).getTime() -
            new Date(this.formData.startTime).getTime();
          if (diff < 0) {
            this.$message({
              message: "计划完成时间必须大于计划开始时间！",
              type: "error"
            });
            return;
          }
          if (this.devices.length == 0) {
            this.$message({
              message: "请选择巡检设备和巡检项目",
              type: "error"
            });
            return;
          }
          // for (var i = 0; i < this.devices.length; i++) {
          //   if (!this.devices[i].proid) {
          //     this.$message({
          //       message: `请选择设备【${this.devices[i].name}】关联的巡检标准`,
          //       type: "error"
          //     });
          //     return;
          // this.$alert(
          //   `请选择设备【${this.devices[i].name}】关联的巡检标准`,
          //   "提示",
          //   {
          //     confirmButtonText: "知道啦"
          //   }
          // );
          // return;
          // }
          // }
          /**
           * 以下逻辑为：
           * 先遍历所有的设备，相同的设备id存放在一个数组字典里
           * 然后遍历这个数据字典，循环加载出项目
           */
          // let detailArray = [];
          // var dList = {};
          // for (var i = 0; i < this.devices.length; i++) {
          //   var item = this.devices[i];
          //   var id = this.devices[i].id;
          //   if (!dList[id]) {
          //     dList[id] = [item];
          //   } else {
          //     dList[id].push(item);
          //   }
          // }
          // for (var i in dList) {
          //   let projectid = [];
          //   dList[i].forEach(p => {
          //     projectid.push(p.proid);
          //   });
          //   let obj = { deviceId: i, projectId: projectid };
          //   detailArray.push(obj);
          // }
          let info = [];
          if (this.devices.length > 0) {
            this.devices.map(el =>
              info.push({ deviceId: el.id, qy: el.qy ? 1 : 0 })
            );
          } else {
            this.$message.error("请选择巡检标准");
            return false;
          }
          this.formData.deviceIds = JSON.stringify(info);
          let pro = [];
          if (this.proList.length > 0) {
            this.proList.map(el => pro.push(el.id));
          } else {
            this.$message.error("请选择巡检标准");
            return false;
          }
          this.formData.projectIds = JSON.stringify(pro);
          if (this.isDisabled) {
            return;
          }
          this.isDisabled = true;
          this.$api.patroPlanAPI.addPlan(this.formData).then(res => {
            this.isDisabled = false;
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.back();
            } else {
              this.$message({
                message: res.msg,
                type: "error"
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 保存
     */
    tempSave(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          if (this.devices.length == 0) {
            this.$message({
              message: "请选择巡检设备和巡检项目",
              type: "error"
            });
            return;
          }
          // for (var i = 0; i < this.devices.length; i++) {
          //   if (!this.devices[i].proid) {
          //     this.$message({
          //       message: `请选择设备【${this.devices[i].name}】关联的巡检标准`,
          //       type: "error"
          //     });
          //     return;
          // this.$alert(
          //   `请选择设备【${this.devices[i].name}】关联的巡检标准`,
          //   "提示",
          //   {
          //     confirmButtonText: "知道啦"
          //   }
          // );
          // return;
          // }
          // }
          // let detailArray = [];
          // var dList = {};
          // for (var i = 0; i < this.devices.length; i++) {
          //   var item = this.devices[i];
          //   var id = this.devices[i].id;
          //   if (!dList[id]) {
          //     dList[id] = [item];
          //   } else {
          //     dList[id].push(item);
          //   }
          // }
          // for (var i in dList) {
          //   let projectid = [];
          //   dList[i].forEach(p => {
          //     projectid.push(p.proid);
          //   });
          //   let obj = { deviceId: i, projectId: projectid };
          //   detailArray.push(obj);
          // }
          // this.formData.detailArray = JSON.stringify(detailArray);
          let info = [];
          if (this.devices.length > 0) {
            this.devices.map(el =>
              info.push({ deviceId: el.id, qy: el.qy ? 1 : 0 })
            );
          } else {
            this.$message.error("请选择巡检标准");
            return false;
          }
          this.formData.deviceIds = JSON.stringify(info);
          let pro = [];
          if (this.proList.length > 0) {
            this.proList.map(el => pro.push(el.id));
          } else {
            this.$message.error("请选择巡检标准");
            return false;
          }
          this.formData.projectIds = JSON.stringify(pro);
          if (this.isDisabled) {
            return;
          }
          this.isDisabled = true;
          this.$api.patroPlanAPI.addPlanTS(this.formData).then(res => {
            this.isDisabled = false;
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.back();
            } else {
              this.$message({
                message: res.msg,
                type: "error"
              });
            }
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.el-input-number {
  width: 140px !important;
}
.flex {
  display: flex;
  flex-wrap: wrap;
}
.sys-form {
  padding: 20px 20px 20px 20px;
}
.sys-form .form-inline {
  width: 33.33%;
}
.sys-form .form-line {
  width: 66.66%;
}
.sys-form .form-half {
  width: 50%;
}
.sys-form .form-inline .el-input,
.sys-form .form-inline .el-select .el-input {
  width: 100%;
}
.sys-form .form-short .el-input,
.sys-form .form-short .el-select .el-input {
  margin-right: 5px;
  width: 100px;
}
.icon-luyin {
  color: #2589ee;
  font-size: 24px;
  cursor: pointer;
}
.form-ts {
  padding-left: 20px;
  color: #aaa;
  display: inline-block;
}
.el-form-item__content .sys-operate {
  padding: 10px 0px;
}
</style>
<style>
.plan-box .sys-form .form-inline .el-select,
.plan-box .sys-form .form-inline .el-select .el-input {
  width: 100%;
}
.plan-box .el-table thead {
  line-height: 1;
}
.el-input-number .el-input {
  width: 100% !important;
}
</style>
