
<style lang="less" scoped>
  .addPlanWrapper {
    padding: 20px 60px 120px 60px;
    margin: 70px 20px 0 20px;
    background: #fff;
    .topBack {
      top: 0;
      left: 0;
    }
    ul {
      li {
      }
    }
    .group_item {
      border-bottom: 1px solid #eee;
      .item_title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: #f2f2f2;
        .title_left {
          display: flex;
          justify-content: center;
          align-items: center;
          .handleIcon {
            display: flex;
            align-items: center;
            margin: 0 5px;
            cursor: pointer;
            img {
              width: 20px;
              height: 20px;
            }
          }
        }

        .title_right {
          .titlwSwitchStatus {
            margin: 0 22px 0 16px;
          }
        }
      }
      ul {
        li {
          display: flex;
          .move_btn {
            display: flex;
            height: 40px;
            .move_top,
            .move_down {
              width: 30px;
              .img_box {
                width: 100%;
                height: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
              }
              .ispointer {
                cursor: pointer;
              }
              img {
                width: 10px;
                height: 14px;
              }
            }
            .move_top {
              img {
                margin-top: -15px;
              }
            }
          }
          .list_item_title {
            width: 140px;
          }
          .list_item_swich {
            .planStatus {
              margin-left: 16px;
            }
          }

          .list_right {
            // width: calc(100% - 60px);
            flex: 1;
            display: flex;
            justify-content: space-between;
            .right_l {
              display: flex;
              // width: calc(100% - 200px);
            }
            /deep/.el-input--small {
              width: 60px;
            }
          }
          .list_right1 {
            width: calc(100%);
          }
        }
      }
    }
    .open {
      transform: rotate(0deg);
      transition: transform 0.3s;
    }
    .close {
      transform: rotate(180deg);
      transition: transform 0.3s;
    }
    .plus-icon-enter-active {
      transition: all 0.3s;
    }
    .plus-icon-enter {
      opacity: 0;
    }
    .plus-icon-leave-active {
      transition: all 0.3s;
    }
    .plus-icon-leave-active {
      opacity: 0;
    }
  }
</style>
<template>
  <el-scrollbar style="height: 100%" ref="elscrollbar">
    <div class="addPlanWrapper">
      <crumbs
              :title="
          isEdit ? '电子病历方案配置-修改方案' : '电子病历方案配置-添加方案'
        "
              class="topBack"
              :param="$route.params"
              linkTo="Plan"
      ></crumbs>
      <el-row>
        <el-col :span="16">
          <el-form ref="form" :model="form" label-width="80px" :rules="rules">
            <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="可输入字母、数字和下划线"
              ></el-input>
            </el-form-item>
            <el-form-item label="方案配置">
              <div
                      class="group_item"
                      v-for="(group, i) in form.planDetailSub"
                      :key="group.id"
              >
                <div class="item_title">
                  <div class="title_left">
                    <div class="handleIcon" @click="listShow(i)">
                      <img
                              src="../../../images/multi.png"
                              :alt="group.name"
                              :class="isOpenCloseItems[i] ? 'open' : 'close'"
                      />
                    </div>
                    <h4>{{ group.name }}</h4>
                  </div>
                  <div class="title_right">
                    <el-switch
                            v-model="group.status"
                            :active-value="1"
                            :inactive-value="0"
                            active-color="#4BC4D7"
                            inactive-color="#BBBBBB"
                    ></el-switch>
                    <span class="titlwSwitchStatus">{{
                      group.status === 1 ? "启用中" : "未启用"
                    }}</span>
                  </div>
                </div>
                <transition name="plus-icon">
                  <ul v-show="isOpenCloseItems[i]">
                    <li
                            v-for="(item, index) in group.planDetails"
                            :key="item.id"
                    >
                      <div class="move_btn">
                        <div class="move_top">
                          <div
                                  class="img_box ispointer"
                                  v-if="index !== 0 && ismix(item.name)"
                                  @mouseover="upActive = index"
                                  @mouseout="upActive = null"
                                  @click="
                              handleMove('up', {
                                name: item.name,
                                orderNo: item.orderNo,
                                groupIndex: i,
                                itemIndex: index
                              })
                            "
                          >
                            <img
                                    :src="
                                upActive === index
                                  ? require('../../../images/icon_hover_top.png')
                                  : require('../../../images/icon_default_top.png')
                              "
                            />
                          </div>
                          <div class="img_box" v-else></div>
                        </div>
                        <div class="move_down">
                          <div
                                  class="img_box ispointer"
                                  v-if="
                              index !== group.planDetails.length - 1 &&
                              ismix(item.name)
                            "
                                  @mouseover="downActive = index"
                                  @mouseout="downActive = null"
                                  @click="
                              handleMove('down', {
                                name: item.name,
                                orderNo: item.orderNo,
                                groupIndex: i,
                                itemIndex: index
                              })
                            "
                          >
                            <img
                                    :src="
                                downActive === index
                                  ? require('../../../images/icon_hover_down.png')
                                  : require('../../../images/icon_default_down.png')
                              "
                            />
                          </div>
                          <div class="img_box" v-else></div>
                        </div>
                      </div>
                      <div class="list_right" v-if="!item.list">
                        <div class="list_right">
                          <div class="right_l">
                            <div class="list_item_title">
                              {{ item.name }}
                            </div>
                            <div class="list_item_swich">
                              <el-switch
                                      v-model="item.status"
                                      :active-value="1"
                                      :inactive-value="0"
                                      active-color="#4BC4D7"
                                      inactive-color="#BBBBBB"
                              ></el-switch>
                              <span class="planStatus">{{
                                item.status === 1 ? "启用中" : "未启用"
                              }}</span>
                            </div>
                          </div>
                          <div v-if="item.number">
                            <span style="margin-right: 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>
                        </div>
                      </div>
                      <div v-else style="width: 100%">
                        <div
                                class="list_right list_right1"
                                v-for="child in item.list"
                                :key="child.id"
                        >
                          <div class="right_l">
                            <div class="list_item_title">
                              {{ child.name }}
                            </div>
                            <div class="list_item_swich">
                              <el-switch
                                      v-model="child.status"
                                      :active-value="1"
                                      :inactive-value="0"
                                      active-color="#4BC4D7"
                                      inactive-color="#BBBBBB"
                              ></el-switch>
                              <span class="planStatus">{{
                                child.status === 1 ? "启用中" : "未启用"
                              }}</span>
                            </div>
                          </div>
                          <div v-if="child.number">
                            <span style="margin-right: 8px">默认显示个数</span>
                            <el-select
                                    v-model="child.number"
                                    placeholder="请选择"
                                    size="small"
                                    :disabled="child.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>
                        </div>
                      </div>
                    </li>
                  </ul>
                </transition>
              </div>
            </el-form-item>
            <el-form-item>
              <div>
                <el-button style="float: right" type="primary" @click="onSubmit"
                >确定</el-button
                >
              </div>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </el-scrollbar>
</template>

<script>
    import api from "@api/icss.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 {
                upActive: null,
                downActive: null,
                isEdit: false,
                hospitalId: null,
                form: {
                    hospitalId: "",
                    planName: "",
                    planCode: "",
                    planStatus: 1,
                    planDetailSub: []
                },
                isOpenCloseItems: { 0: true }, // 是否展开方案配置项
                rules: {
                    planName: [
                        { 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" },
                        { required: true, validator: validatePass1, trigger: "blur" }
                    ]
                },
                mixArr: ["开单合理性", "高危", "危急值提醒", "其他提醒"],
                newList: []
            };
        },
        methods: {
            //展开收起控制
            listShow(i) {
                // TODO Vue监听不到对象中新添加的项，所以复制一份
                let obj = { ...this.isOpenCloseItems };
                obj[i] === true ? (obj[i] = false) : (obj[i] = true);
                this.isOpenCloseItems = obj;
            },
            onSubmit() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        const hospitalId = this.$route.params.hospitalId;
                        let params = JSON.parse(JSON.stringify(this.form));
                        params.hospitalId=hospitalId;
                        params.planDetailParent = params.planDetailSub;
                        delete params.planDetailSub;
                        let arr = [];
                        let index = null;
                        params.planDetailParent[0].planDetails.forEach((item, i) => {
                            if (item.name === "开单合理性") {
                                arr.push(...item.list);
                                index = i;
                            }
                        });
                        params.planDetailParent[0].planDetails.splice(index, 1, ...arr);
                      console.log(this.$route.params)
                        params.planDetailParent = params.planDetailParent.map((item) => {
                            let newArr = [];
                            if (item.planDetails) {
                                newArr = item.planDetails.map((child) => {
                                    return {
                                        code: child.code,
                                        hospitalId: hospitalId,
                                        name: child.name,
                                        number: child.number,
                                        orderNo: child.orderNo,
                                        planId: child.planId,
                                        remark: child.remark,
                                        status: child.status,
                                        value: child.value
                                    };
                                });
                            }
                            return {
                                code: item.code,
                                hospitalId: hospitalId,
                                name: item.name,
                                number: item.number,
                                orderNo: item.orderNo,
                                planDetailSub: newArr,
                                status: item.status
                            };
                        });
                        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;
                        });
                    }
                });
            },
            ismix(val) {
                const index = this.mixArr.findIndex((item) => item == val);
                if (index <= 0) {
                    return true;
                }
                return false;
            },
            handleMove(type, obj) {
                /**
                 * @params
                 *    type:up/down
                 *    obj:{
       *      orderNo:当前点击项的orderNo,
       *      itemIndex:当前点击项的index,
       *      groupIndex:当前组的index
       *    }
                 */
                const { name, orderNo, itemIndex, groupIndex } = obj;
                // exIndex获取到要交换的Index值
                let exIndex = type === "up" ? itemIndex - 1 : itemIndex + 1;
                // exOrderNo获取到要交换的orderNo
                const exOrder = this.form.planDetailSub[groupIndex].planDetails[exIndex];
                // 赋值一份新的数据
                let newList = JSON.parse(
                    JSON.stringify(this.form.planDetailSub[groupIndex].planDetails)
                );
                // 交换orderNo
                newList[exIndex].orderNo = orderNo;
                newList[itemIndex].orderNo = exOrder.orderNo;
                if (newList[itemIndex].list) {
                    newList[itemIndex].list[0].orderNo = exOrder.orderNo;
                }

                // 排序
                newList = this.groupSort(newList);
                // 更新数据
                this.form.planDetailSub[groupIndex].planDetails = newList;
            },
            // 初始化
            fomatArr() {
                let oneArr = JSON.parse(
                    JSON.stringify(this.form.planDetailSub[0].planDetails)
                );
                // const index = this.mixArr.findIndex((item) => item == val);
                let list = oneArr.filter((ite) => {
                    const j = this.mixArr.findIndex((itemB) => itemB === ite.name);
                    return j !== -1;
                });
                let biglist = oneArr.filter((ite) => {
                    const j = this.mixArr.findIndex((itemB) => itemB === ite.name);
                    return j === -1;
                });
                let obj = { list };
                list.forEach((child) => {
                    if (child.name === "开单合理性") {
                        obj.orderNo = child.orderNo;
                        obj.name = child.name;
                        obj.id = child.id + "d";
                    }
                });
                biglist.push(obj);
                this.form.planDetailSub[0].planDetails = this.groupSort(biglist);
            },
            getDefaultPlans() {
                api.getDefaultPlans().then((res) => {
                    if (res.data.code === "0") {
                        this.form.planDetailSub = res.data.data.planDetailDefault;
                        this.fomatArr();
                    }
                });
            },
            // 相应数组排序
            groupSort(arr) {
                if (Array.isArray(arr)) {
                    for (let i = arr.length - 1; i > 0; i--) {
                        for (let j = 0; j < i; j++) {
                            if (arr[j].orderNo > arr[j + 1].orderNo) {
                                [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
                            }
                        }
                    }
                    return arr;
                }
            },
            // 编辑获取默认数据
            async getPlanInfoIds(params) {
                try {
                    const res = await api.getPlanInfoIds(params);
                    if (res.data.code === "0") {
                        const obj = res.data.data[0];
                        const { data } = this.$route.params;
                        this.form = {
                            hospitalId: obj.hospitalId,
                            planName: obj.planName,
                            planCode: obj.planCode,
                            planStatus: obj.planStatus||1,
                            planDetailSub: obj.sysSetInfo,
                            id: data.id
                        };

                        const defaultRes = await api.getDefaultPlans();
                        if (defaultRes.data.code === "0") {
                            // 合并默认数据
                            this.mergeDefaultPlans(defaultRes.data.data.planDetailDefault);
                        }
                    }
                } catch (err) {
                    console.error("err", err);
                }
            },
            // 合并默认数据
            mergeDefaultPlans(data) {
                if (!this.form.planDetailSub) {
                    this.form.planDetailSub = data;
                    return;
                }
                data.forEach((item) => {
                    const oneIndex = this.form.planDetailSub.findIndex(
                        (ite) => ite.name === item.name
                    );
                    // 第一层数据不存在的话，直接加入进去

                    if (oneIndex === -1) {
                        item.status = 0;
                        this.form.planDetailSub.push(item);
                    } else if (!this.form.planDetailSub[oneIndex].planDetails) {
                        this.form.planDetailSub[oneIndex].planDetails = item.planDetails;
                    } else {
                        // 第一层数据存在，验证第二层
                        item.planDetails &&
                        item.planDetails.forEach((child) => {
                            const twoArr = this.form.planDetailSub[oneIndex].planDetails;
                            const childIndex = twoArr
                                ? twoArr.findIndex((it) => it.name === child.name)
                                : null;
                            // 第二层数据不存在，直接添加进去
                            if (childIndex && childIndex === -1) {
                                child.status = 0;
                                this.form.planDetailSub[oneIndex].planDetails.push(child);
                            }
                        });
                    }
                });
                // 排序
                const newData = this.groupSort(this.form.planDetailSub);
                newData.forEach((sun) => {
                    if (sun.planDetails) {
                        this.groupSort(sun.planDetails);
                    }
                });
                this.fomatArr();
            }
        },

        created() {
            const { isEdit, data } = this.$route.params;
            if (isEdit) {
                // 编辑页面
                this.isEdit = true;

                let params = {
                    hospitalId: data.hospitalId,
                    id: data.id
                };
                this.getPlanInfoIds(params);
            } else {
                // 新增页面
                this.getDefaultPlans(); // 获取默认配置信息
            }
        }
    };
</script>
