<template>
  <el-scrollbar style="height: 100%" ref="elscrollbar">
    <div class="AddPlanWrapper clearfix" @click="close">
      <crumbs
        :title="isEdit ? '电子病历方案配置-修改方案' : '电子病历方案配置-添加方案'"
        class="topBack"
        :param="$route.params"
        linkTo="Plan"
      ></crumbs>
      <div class="AddPlanBox">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form ref="form" :model="form" label-width="80px" :rules="rules">
              <!-- <el-form-item label="医院名称" prop="hoipitalName">
                <el-input v-model="form.planName" placeholder="2-30位,可输入汉字、字母、数字和下划线"></el-input>
              </el-form-item>-->
              <el-form-item label="医院名称" class="selectMedicine" prop="hospitalId">
                <el-select
                  v-model="form.hospitalId"
                  placeholder="请选择"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in HospitalInfoList"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="方案名称" prop="planName">
                <el-input v-model="form.planName" placeholder="2-30位,可输入汉字、字母、数字和下划线"></el-input>
              </el-form-item>
              <el-form-item label="方案编码" prop="planCode">
                <el-input v-model="form.planCode" placeholder="4-15位,可输入字母、数字和下划线"></el-input>
              </el-form-item>
              <el-form-item label="方案配置">
                <ul>
                  <li>
                    <div class="title">
                      <div class="handleIcon" @click="openPlanItems">
                        <img
                          src="../../../images/multi.png"
                          alt="辅助信息"
                          :class="{'open' : isOpenCloseItems}"
                        />
                      </div>
                      <h4>辅助信息</h4>
                      <div class="titlwSwitch">
                        <el-switch
                          v-model="switchSubStatus"
                          :active-value="1"
                          :inactive-value="0"
                          active-color="#4BC4D7"
                          inactive-color="#BBBBBB"
                        ></el-switch>
                        <span class="titlwSwitchStatus">{{switchSubStatus === 1 ? '启用中' : '未启用'}}</span>
                      </div>
                    </div>
                    <transition name="plus-icon">
                      <div v-if="isOpenCloseItems">
                        <ul class="sub" v-for="(item,index) in  planDefaultList" :key="item.id">
                          <li class="planItem">
                            <div class="sort">
                              <div class="top">
                                <img
                                  :src="isTopLight !== index ? require('../../../images/icon_default_top.png') : require('../../../images/icon_hover_top.png')"
                                  alt="上升"
                                  v-if="index !== 0"
                                  @click="sortPlan(item,index,'top')"
                                  @mouseover="handleMouseEnter1(index)"
                                  @mouseleave="handleMouseLeave1(index)"
                                />
                              </div>
                              <div class="down">
                                <img
                                  :src="isDownLight !== index ? require('../../../images/icon_default_down.png') : require('../../../images/icon_hover_down.png')"
                                  alt="下降"
                                  v-if="index !== planDefaultList.length - 1"
                                  @click="sortPlan(item,index,'down')"
                                  @mouseover="handleMouseEnter(index)"
                                  @mouseleave="handleMouseLeave(index)"
                                />
                              </div>
                            </div>
                            <div class="openOrClose">
                              <span class="planInfo">{{item.name}}</span>
                              <div class="switch">
                                <el-switch
                                  v-model="item.status"
                                  :active-value="1"
                                  :inactive-value="0"
                                  active-color="#4BC4D7"
                                  inactive-color="#BBBBBB"
                                ></el-switch>
                              </div>
                              <span class="planStatus">{{item.status === 1 ? '启用中' : '未启用'}}</span>
                            </div>
                            <div class="showNum" v-if="item.number">
                              <span style="marginRight:8px;">默认显示个数</span>
                              <el-select
                                v-model="item.number"
                                placeholder="请选择"
                                size="small"
                                :disabled="item.status !== 1 ? true: false"
                              >
                                <el-option label="1" value="1"></el-option>
                                <el-option label="2" value="2"></el-option>
                                <el-option label="3" value="3"></el-option>
                                <el-option label="4" value="4"></el-option>
                                <el-option label="5" value="5"></el-option>
                                <el-option label="6" value="6"></el-option>
                              </el-select>
                            </div>
                          </li>
                        </ul>
                      </div>
                    </transition>
                  </li>
                  <li>
                    <div class="title">
                      <div class="handleIcon">
                        <img src="../../../images/multi.png" alt="医学知识" />
                      </div>
                      <h4>医学知识</h4>
                      <div class="titlwSwitch">
                        <el-switch
                          v-model="switchMedStatus"
                          :active-value="1"
                          :inactive-value="0"
                          active-color="#4BC4D7"
                          inactive-color="#BBBBBB"
                        ></el-switch>
                        <span class="titlwSwitchStatus">{{switchMedStatus === 1 ? '启用中' : '未启用'}}</span>
                      </div>
                    </div>
                  </li>
                  <li>
                    <div class="title">
                      <div class="handleIcon">
                        <img src="../../../images/multi.png" alt="医学知识" />
                      </div>
                      <h4>随访计划</h4>
                      <div class="titlwSwitch">
                        <el-switch
                          v-model="switchFollowStatus"
                          :active-value="1"
                          :inactive-value="0"
                          active-color="#4BC4D7"
                          inactive-color="#BBBBBB"
                        ></el-switch>
                        <span class="titlwSwitchStatus">{{switchFollowStatus === 1 ? '启用中' : '未启用'}}</span>
                      </div>
                    </div>
                  </li>
                </ul>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit" :disabled="saveDisable">确定</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </div>
  </el-scrollbar>
</template>
<script>
import api from '@api/cdss.js';

export default {
  name: 'AddPlan',
  data() {
    var numreg = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
    var numreg1 = /^[0-9a-zA-Z_]{1,}$/;
    var validatePass = (rule, value, callback) => {
      if (!numreg.test(value)) {
        callback(new Error('汉字、字母、数字和下划线'));
      } else {
        callback();
      }
    };
    var validatePass1 = (rule, value, callback) => {
      if (!numreg1.test(value)) {
        callback(new Error('字母、数字和下划线'));
      } else {
        callback();
      }
    };
    return {
      form: {
        hospitalId: '',
        planName: '',
        planCode: ''
      },
      saveDisable: false, //保存按钮禁止点击
      rules: {
        planName: [
          { required: true, message: '方案名称不能为空', trigger: 'change' },
          { min: 2, max: 30, message: '长度2-30位', trigger: 'blur' },
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        hospitalId: [
          { required: true, message: '医院名称不能为空', trigger: 'change' }
          // { min: 2, max: 30, message: '长度2-30位', trigger: 'blur' },
          // { required: true, validator: validatePass, trigger: 'blur' }
        ],
        planCode: [
          { required: true, message: '方案编码不能为空', trigger: 'change' },
          { min: 4, max: 15, message: '长度4-15位', trigger: 'blur' },
          { required: true, validator: validatePass1, trigger: 'blur' }
        ]
      },
      planDefaultList: [],
      // hospitalId: '',
      isEdit: false, // 是否处于编辑页面 false--新增   true--编辑
      switchSubStatus: 0, // 辅助信息
      switchMedStatus: 0, // 医学知识
      switchFollowStatus: 0, //随访计划
      isOpenCloseItems: true, // 是否展开方案配置项
      isDownLight: -1,
      isTopLight: -1,
      flag: 1,
      editCount: -1, // 页面会否被编辑 >0被编辑   =0 未编辑
      isSaveSuccess: false, // 是否保存成功
      HospitalInfoList: []
    };
  },
  beforeRouteLeave(to, from, next) {
    console.log(this.editCount,'this.editCount');
    if (
      (this.editCount > 3 && !this.isSaveSuccess && this.isEdit) ||
      (this.editCount > 1 && !this.isSaveSuccess && !this.isEdit)
    ) {
      // console.log('页面被编辑了');
      this.$alert('还有未保存的内容,确定要退出当前页面吗?', '提示', {
        confirmButtonText: '确定',
        // cancelButtonText: '取消',
        // cancelButtonClass: 'leaveBtn',
        // customClass: 'leaveBox',
        type: 'warning'
      })
        .then(() => {
          next();
        })
        .catch(() => {});
    } else {
      next();
    }
  },
  watch: {
    form: {
      handler(newName, oldName) {
        this.editCount++;
      },
      deep: true
      // immediate: true
    },
    planDefaultList: {
      handler(newName, oldName) {
        // console.log(newName,'newName');
        // console.log(oldName,'oldName');
        this.editCount++;
      },
      deep: true,
      immediate: true
    }
  },
  async created() {
    const { isEdit, data } = this.$route.params;
    console.log(data, '编辑页传递的data');
    this._getHospitalInfo(); // 获取医院下拉列表
    // let res = await api.getHospitalInfo(); // 同步获取医院信息
    // this.hospitalId = res.data.data.id;
    if (isEdit) {
      // 编辑页面
      this.isEdit = true;
      this.form.hospitalId = data.hospitalId
      let params = {
        hospitalId: data.hospitalId,
        id: data.id
      };
      this._getPlanInfoIds(params);
    } else {
      // 新增页面
      this._getDefaultPlans(); // 获取默认配置信息
    }
  },
  methods: {
    close() {},
    // 获取医院下拉列表
    _getHospitalInfo() {
      api.getHospitalInfo().then(res => {
        if (res.data.code === '0') {
          this.HospitalInfoList = res.data.data;
        }
      });
    },
    // 方案配置排序
    sortPlan(item, index, type) {
      // console.log('排序', item, index, type);
      let tempList = [...this.planDefaultList];
      if (type === 'down') {
        // 降序
        let plan = tempList.find(item => {
          return item.orderNo === index + 1;
        });
        let tempPlan = { ...plan };
        let planNext = tempList.find(item => {
          return item.orderNo === index + 2;
        });
        let tempPlanNext = { ...planNext };
        plan = tempPlanNext;
        plan.orderNo -= 1;
        planNext = tempPlan;
        planNext.orderNo += 1;
        let arr = tempList.map((i, idx) => {
          if (idx === index) {
            return { ...plan };
          } else if (idx === index + 1) {
            return { ...planNext };
          } else {
            return i;
          }
        });
        this.planDefaultList = [...arr];
      } else {
        // 升序
        let plan = tempList.find(item => {
          return item.orderNo === index + 1;
        });
        let tempPlan = { ...plan };
        let planPre = tempList.find(item => {
          return item.orderNo === index;
        });
        let tempPlanPre = { ...planPre };
        plan = tempPlanPre;
        plan.orderNo += 1;
        planPre = tempPlan;
        planPre.orderNo -= 1;
        let arr = tempList.map((i, idx) => {
          if (idx === index) {
            return { ...plan };
          } else if (idx === index - 1) {
            return { ...planPre };
          } else {
            return i;
          }
        });
        this.planDefaultList = [...arr];
      }
    },

    // 展开列表项
    openPlanItems() {
      this.isOpenCloseItems = !this.isOpenCloseItems;
    },

    // 鼠标移入
    handleMouseEnter(index) {
      this.isDownLight = index;
    },

    // 鼠标移除
    handleMouseLeave(index) {
      this.isDownLight = -1;
    },

    // 鼠标移入
    handleMouseEnter1(index) {
      this.isTopLight = index;
    },

    // 鼠标移除
    handleMouseLeave1(index) {
      this.isTopLight = -1;
    },

    // 获取默认方案配置
    _getDefaultPlans() {
      api.getDefaultPlans().then(res => {
        console.log(res, '获取默认的方案配置');
        if (res.data.code === '0') {
          this.planDefaultList =
            res.data.data &&
            res.data.data.planDetailDefault.length !== 0 &&
            res.data.data.planDetailDefault[0].planDetails;
          this.switchSubStatus =
            res.data.data &&
            res.data.data.planDetailDefault.length !== 0 &&
            res.data.data.planDetailDefault[0].status;
          this.switchMedStatus =
            res.data.data &&
            res.data.data.planDetailDefault.length !== 0 &&
            res.data.data.planDetailDefault[1].status;
          this.switchFollowStatus =
            res.data.data &&
            res.data.data.planDetailDefault.length !== 0 &&
            res.data.data.planDetailDefault[2].status;
        }
      });
    },

    // 编辑页面 根据id获取方案配置
    async _getPlanInfoIds(params) {
      // 先获取默认的所有方案
      let tempArr = [];
      let newPlan = [];
      let res = await api.getDefaultPlans();
      if (res.data.code === '0') {
        tempArr =
          res.data.data &&
          res.data.data.planDetailDefault.length !== 0 &&
          res.data.data.planDetailDefault[0].planDetails;
      }
      let res1 = await api.getPlanInfoIds(params);
      console.log(res1, '==================');
      if (res1.data.code === '0') {
        newPlan = res1.data.data[0].sysSetInfo[0].planDetails;
        this.form.planName = res1.data.data[0].planName;
        this.form.planCode = res1.data.data[0].planCode;
        this.switchSubStatus = res1.data.data[0].sysSetInfo[0].status;
        this.switchMedStatus = res1.data.data[0].sysSetInfo[1].status;
        this.switchFollowStatus = res1.data.data[0].sysSetInfo[2].status;
        // this.planDefaultList = res1.data.data[0].sysSetInfo[0].planDetails;
      }
      let arr = [];
      let arrTemp = [];
      let arrTemp1 = []; // 不同index
      for (var i = 0; i < tempArr.length; i++) {
        arrTemp.push(i);
      }
      for (var i = 0; i < tempArr.length; i++) {
        for (var j = 0; j < newPlan.length; j++) {
          if (tempArr[i].code === newPlan[j].code) {
            arr.push(i);
          }
        }
      }
      arrTemp1 = arr
        .filter(x => arrTemp.indexOf(x) == -1)
        .concat(arrTemp.filter(x => arr.indexOf(x) == -1));
      let endArr = [...newPlan];
      for (var j = 0; j < arrTemp1.length; j++) {
        let temp = tempArr[arrTemp1[j]];
        temp.orderNo = arr.length + j + 1;
        temp.status = 0;
        endArr.push(temp);
      }
      // console.log(endArr,'-=-=-=-=-=');
      this.planDefaultList = endArr;
    },

    // format处理细项数据
    handleSendData() {
      let TempPlanDetail = [];
      TempPlanDetail = this.planDefaultList.map((item, index) => {
        return {
          code: item.code,
          hospitalId: this.form.hospitalId,
          // hospitalId: this.hospitalId,
          name: item.name,
          number: item.number,
          orderNo: item.orderNo,
          planId: item.planId,
          remark: item.remark,
          status: item.status,
          value: item.value
        };
      });
      return TempPlanDetail;
      // console.log(TempPlanDetail, 'TempPlanDetail');
    },

    // 处理保存活动信息参数
    _getParams() {
      let params = {
        hospitalId: this.form.hospitalId,
        planCode: this.form.planCode,
        planDetailParent: [
          {
            code: 'auxiliary',
            hospitalId: this.form.hospitalId,
            name: '辅助信息',
            number: 0,
            orderNo: 1,
            planDetailSub: this.handleSendData(),
            status: this.switchSubStatus
          },
          {
            code: 'medical',
            hospitalId: this.form.hospitalId,
            name: '医学知识',
            orderNo: 3,
            planDetailSub: [{}],
            status: this.switchMedStatus
          },
          {
            code: 'followup',
            hospitalId: this.form.hospitalId,
            name: '随访计划',
            orderNo: 4,
            planDetailSub: [{}],
            status: this.switchFollowStatus
          }
        ], // 方案配置信息
        planName: this.form.planName,
        planStatus: 1 // 1 启用    默认启用
      };
      if (this.isEdit) {
        // 编辑状态,需要额外添加ID
        const { data } = this.$route.params;
        params = { ...params, id: data.id };
      }
      return params;
    },

    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.saveDisable = true;
          let params = this._getParams();
          // console.log(params, 'params');
          // return;
          api.savePlanInfoDatas(params).then(res => {
            if (res.data.code === '0') {
              this.$message({
                showClose: true,
                message: '保存成功',
                type: 'success',
                duration: 1000
              });
              this.isSaveSuccess = true; // 保存成功,可正常退出
              this.$router.push({
                name: 'Plan',
                params: Object.assign({}, this.$route.params, {
                  currentPage: 1
                })
              });
            } else if (res.data.code === '00020007') {
              // 方案名/方案编码已存在
              this.$message({
                showClose: true,
                message: res.data.msg,
                type: 'error',
                duration: 1000
              });
            }
            this.saveDisable = false;
          });
        } else {
          this.saveDisable = false;
          var div = this.$refs['elscrollbar'].$refs['wrap'];
          this.$nextTick(() => {
            div.scrollTop = 0;
          });
          return false;
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
.AddPlanWrapper {
  min-width: 940px;
  .AddPlanBox {
    padding: 20px 60px 120px 60px;
    margin: 70px 20px 0 20px;
    background: #fff;
  }
  color: #606266;
  .topBack {
    top: 0;
  }
  .title {
    background-color: #f2f2f2;
    display: flex;
    .handleIcon {
      width: 30px;
      cursor: pointer;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      img {
        width: 20px;
        height: 20px;
      }
      .open {
        transform: rotate(180deg);
      }
      .close {
        transform: rotate(0deg);
      }
    }
    .titlwSwitch {
      width: 120px;
    }
    h4 {
      flex: 1;
    }
    .titlwSwitchStatus {
      margin-left: 16px;
    }
  }
  .sub {
    .planItem {
      display: flex;
      .sort {
        width: 60px;
        display: flex;
        .top {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 30px;
          cursor: pointer;
          img {
            width: 10px;
            height: 14px;
          }
        }
        .down {
          width: 30px;
          cursor: pointer;
          display: flex;
          justify-content: center;
          align-items: center;
          img {
            width: 10px;
            height: 14px;
          }
        }
      }
      .openOrClose {
        display: flex;
        flex: 1;
        .planInfo {
          width: 140px;
        }
        .switch {
        }
        .planStatus {
          margin-left: 16px;
        }
      }
      .showNum {
        display: flex;
        width: 160px;
        /deep/.el-input--small {
          width: 60px;
        }
      }
    }
  }
  .el-button {
    float: right;
  }
  .plus-icon-enter-active {
    transition: all 0.8s;
  }
  .plus-icon-enter {
    opacity: 0;
    margin-top: 12px;
  }
  .plus-icon-leave-active {
    transition: all 0.8s;
  }
  .plus-icon-leave-active {
    opacity: 0;
    margin-top: 12px;
  }
}
.leaveBox {
  /deep/ .leaveBtn {
    // margin-right: 46px;
    background-color: #d7d7d7 !important;
    border-color: transparent;
  }
}
.selectMedicine {
  /deep/ .el-input__suffix-inner {
    position: relative;
    top: -1px;
  }
  /deep/ .el-icon-circle-close {
    position: relative;
    top: -2px;
  }
}
</style>
