<template>
  <div class="main_root">
    <div class="add_strategy_info">
      <div class="add_strategy_left">
        <div class="name_form">
          <div class="name_form_item">名称</div>
          <Input
            placeholder="请输入名称"
            v-model="appStrategyInfo.name"
          ></Input>
        </div>
        <div class="time_strategy">
          时间策略
          <div class="time_tip">
            （应用列表中选中的应用只能在限制的时间内使用）
          </div>
        </div>
        <TimeStrategy
          :times="tempStrategyInfo.times"
          @timesChange="timesChange"
        ></TimeStrategy>
        <div class="action_btns">
          <Button @click="toResetStrategy()">取消</Button>
          <Button type="primary" class="primary_btn" @click="toAddStrategySet()"
            >添加当前设置</Button
          >
        </div>
      </div>
      <div class="add_strategy_right">
        <div class="optional_applications">
          <div>可选应用</div>
          <div>
            <Checkbox
              :disabled="appList.length === 0"
              :value="appAllCheck"
              @on-change="appAllCheckChange"
              >全选</Checkbox
            >
          </div>
        </div>
        <div class="app_list">
          <template v-for="appItem in appList">
            <div
              class="app_item"
              :title="appItem.appName"
              :key="appItem.appid"
              v-if="!appStrategyGroupsSelected.includes(appItem.appid)"
              @click="toSelectApp(appItem.appid)"
            >
              <div class="app_item_top">
                <img :src="$api.showImageUrl + appItem.appIcon" />
              </div>
              <div class="app_item_name">
                {{ appItem.appName }}
              </div>
              <div class="app_item_check">
                <Checkbox
                  :value="tempStrategyInfo.apps.includes(appItem.appid)"
                ></Checkbox>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="strategy_list_title" v-if="appStrategyInfo.groups.length > 0">
      应用策略列表
    </div>
    <div
      class="strategy_item"
      v-for="(groupItem, groupIndex) in appStrategyInfo.groups"
      :key="groupIndex"
    >
      <table class="my_table">
        <tr>
          <th colspan="7">
            <div class="table_header">
              <div class="table_header_title">应用策略{{ groupIndex + 1 }}</div>
              <div class="table_header_action">
                <div @click="toEditeGroupItem(groupItem, groupIndex)">编辑</div>
                <div class="del" @click="toDelGroupItem(groupIndex)">删除</div>
              </div>
            </div>
          </th>
        </tr>
        <tr>
          <td v-for="weekItem in weekDay" :key="weekItem.value">
            {{ weekItem.label }}
          </td>
        </tr>
        <tr>
          <td v-for="weekItem in weekDay" :key="weekItem.value">
            <div class="time_list">
              <span
                v-for="(timeItem, timeIndex) in appStrategyGroupInfo[
                  groupIndex
                ] && appStrategyGroupInfo[groupIndex][weekItem.value]"
                :key="timeIndex"
                >{{ timeItem.starttime }} - {{ timeItem.stoptime }}</span
              >
            </div>
          </td>
        </tr>
        <tr>
          <td colspan="7">
            <div class="table_app_list">
              <div
                class="table_app_item"
                v-for="appid in groupItem.apps"
                :key="appid"
              >
                <div class="app_top">
                  <img
                    v-if="appsInfo[appid]"
                    :src="$api.showImageUrl + appsInfo[appid].appIcon"
                  />
                </div>
                <div class="app_name">
                  {{ appsInfo[appid] && appsInfo[appid].appName }}
                </div>
              </div>
            </div>
          </td>
        </tr>
      </table>
    </div>
    <div class="bottom_btns">
      <Button @click="toGoBack()">返回</Button>
      <Button type="primary" class="primary_btn" @click="toSaveAppStrategy()"
        >确定</Button
      >
    </div>
  </div>
</template>

<script>
import { weekDay } from "@/utils";
import TimeStrategy from "@/components/TimeStrategy/TimeStrategy";
import { app_list_sel } from "@/api/appgroup";
import { stApp_edit, stApp_detail } from "@/api/stPad";
export default {
  components: {
    TimeStrategy
  },
  data() {
    return {
      weekDay,
      // 已选的需要隐藏
      appList: [],
      // 应用策略信息
      appStrategyInfo: {
        stappid: null,
        rversion: null,
        name: "",
        // {apps[appid], times[{week, starttime, stoptime}]}
        groups: []
      },
      // 临时保存策略
      tempStrategyInfo: {
        apps: [],
        times: []
      }
    };
  },
  created() {
    this.getAppList();
    this.getAppStrategyDetail();
  },
  computed: {
    powerParams() {
      return this.$store.getters.powerParams;
    },
    appAllCheck() {
      let allAppids = this.appList.map((appItem) => appItem.appid);
      let isCheck = true;
      for (const appid of allAppids) {
        if (!this.tempStrategyInfo.apps.includes(appid)) {
          isCheck = false;
        }
      }
      return allAppids.length > 0 ? isCheck : false;
    },
    appsInfo() {
      let info = {};
      this.appList.forEach((item) => {
        info[item.appid] = item;
      });
      return info;
    },
    appStrategyGroupInfo() {
      let info = [];
      this.appStrategyInfo.groups.forEach((groupItem) => {
        let groupTimes = {};
        groupItem.times.forEach((timeItem) => {
          if (!groupTimes[timeItem.week]) {
            groupTimes[timeItem.week] = [];
          }
          groupTimes[timeItem.week].push(timeItem);
        });
        info.push(groupTimes);
      });
      return info;
    },
    // 分组已选Appid数组
    appStrategyGroupsSelected() {
      let info = [];
      this.appStrategyInfo.groups.forEach((groupItem) => {
        info.push(...groupItem.apps);
      });
      return info;
    }
  },
  methods: {
    getAppStrategyDetail() {
      stApp_detail({
        rtype: this.powerParams.rtype,
        objectid: this.powerParams.objectid,
        stappid: this.$route.query.stappid
      }).then((data) => {
        if (data.code === 0) {
          this.appStrategyInfo.name = data.obj.name;
          this.appStrategyInfo.groups = data.obj.groups.map((groupItem) => {
            groupItem.apps = groupItem.apps.map((appItem) => appItem.appid);
            return groupItem;
          });
          this.appStrategyInfo.stappid = data.obj.stappid;
          this.appStrategyInfo.rversion = data.obj.rversion;
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    toGoBack() {
      this.$router.go(-1);
    },
    toSaveAppStrategy() {
      if (!this.appStrategyInfo.name) {
        this.$Message.error("请输入名称");
        return;
      }
      if (this.appStrategyInfo.groups.length === 0) {
        this.$Message.error("请添加应用策略");
        return;
      }
      let _groups = this.appStrategyInfo.groups.map((groupItem) => {
        groupItem = JSON.parse(JSON.stringify(groupItem));
        groupItem.apps = groupItem.apps.map((appid) => {
          return { appid };
        });
        return groupItem;
      });
      stApp_edit({
        // rtype: this.powerParams.rtype,
        // objectid: this.powerParams.objectid,
        name: this.appStrategyInfo.name,
        groups: _groups,
        stappid: this.appStrategyInfo.stappid,
        rversion: this.appStrategyInfo.rversion
      }).then((data) => {
        if (data.code === 0) {
          this.toGoBack();
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    toEditeGroupItem(groupItem, groupIndex) {
      this.tempStrategyInfo = JSON.parse(JSON.stringify(groupItem));
      this.appStrategyInfo.groups.splice(groupIndex, 1);
    },
    toDelGroupItem(groupIndex) {
      this.$Modal.confirm({
        title: "提示",
        content: "您确定删除选中数据吗？",
        onOk: () => {
          this.appStrategyInfo.groups.splice(groupIndex, 1);
        },
        onCancel: () => {}
      });
    },
    appAllCheckChange(selected) {
      if (selected) {
        this.tempStrategyInfo.apps = this.appList.map(
          (appItem) => appItem.appid
        );
      } else {
        this.tempStrategyInfo.apps = [];
      }
    },
    toSelectApp(appid) {
      if (this.tempStrategyInfo.apps.includes(appid)) {
        this.tempStrategyInfo.apps = this.tempStrategyInfo.apps.filter(
          (id) => id !== appid
        );
      } else {
        this.tempStrategyInfo.apps.push(appid);
      }
    },
    getAppList() {
      app_list_sel({
        rtype: this.powerParams.rtype,
        objectid: this.powerParams.objectid
      }).then((data) => {
        if (data.code === 0) {
          this.appList = data.obj;
        } else {
          this.appList = [];
          this.$Message.error(data.msg);
        }
      });
    },
    timesChange(times) {
      this.tempStrategyInfo.times = times;
    },
    toResetStrategy() {
      this.tempStrategyInfo = {
        apps: [],
        times: []
      };
    },
    toAddStrategySet() {
      let _tempStrategyInfo = JSON.parse(JSON.stringify(this.tempStrategyInfo));
      // if (_tempStrategyInfo.times.length === 0) {
      //   this.$Message.error("请选择时间范围");
      //   return;
      // }
      if (_tempStrategyInfo.apps.length === 0) {
        this.$Message.error("请选择应用");
        return;
      }
      this.appStrategyInfo.groups.push(_tempStrategyInfo);
      this.toResetStrategy();
    }
  }
};
</script>

<style lang="less" scoped>
.add_strategy_info {
  display: flex;
  justify-content: space-between;
  margin: 16px 16px 0;
  .add_strategy_left {
    width: calc(50% - 20px);
    .name_form {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: bold;
      .name_form_item {
        margin-right: 16px;
        white-space: nowrap;
      }
    }
    .time_strategy {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: bold;
      .time_tip {
        margin-left: 10px;
        font-size: 12px;
        font-weight: normal;
        color: #f0153f;
      }
    }
    .action_btns {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-top: 40px;
      .primary_btn {
        margin-left: 16px;
      }
    }
  }
  .add_strategy_right {
    width: 50%;
    // max-height: 400px;
    overflow: auto;
    .optional_applications {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      line-height: 30px;
      font-weight: bold;
    }
    .app_list {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      width: 100%;
      // max-height: calc(100% - 33px);
      overflow: auto;
      .app_item {
        position: relative;
        margin: 8px;
        width: 100px;
        height: 100px;
        border-radius: 10px;
        border: 1px solid #798cb51a;
        background: #ffffff;
        cursor: pointer;
        &:hover {
          box-shadow: 4px 4px 8px 0 #339dff26;
        }
        .app_item_top {
          display: flex;
          justify-content: center;
          align-items: center;
          margin-top: 10px;
          padding-top: 10px;
          height: calc(100% - 44px);
          img {
            width: 38px;
            height: 38px;
          }
        }
        .app_item_name {
          margin: 10px 0;
          line-height: 1;
          font-size: 14px;
          text-align: center;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .app_item_check {
          position: absolute;
          right: 8px;
          top: 8px;
          /deep/.ivu-checkbox-wrapper {
            margin-right: 0;
            .ivu-checkbox-inner {
              border-radius: 50%;
            }
          }
        }
      }
    }
  }
}
.strategy_list_title {
  margin: 16px;
  font-size: 16px;
  font-weight: bold;
}
.strategy_item {
  margin: 16px;
  .my_table {
    width: 100%;
    empty-cells: show;
    border-collapse: collapse;
    table-layout: fixed;
    border: 1px solid #dcdee2;
    border-spacing: 0;
    box-sizing: border-box;
    font-size: 12px;
    th {
      padding: 0;
      line-height: 30px;
      font-weight: normal;
      text-align: center;
      vertical-align: middle;
      white-space: nowrap;
      background-color: #fff;
      border: 1px solid #ced9f2;
    }
    td {
      position: relative;
      padding: 0;
      line-height: 30px;
      text-align: center;
      vertical-align: middle;
      white-space: nowrap;
      border: 1px solid #ced9f2;
    }
  }
  .table_header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    background-color: #edf3ff;
    .table_header_title {
      font-size: 12px;
      font-weight: bold;
    }
    .table_header_action {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      > div {
        margin-left: 4px;
        padding: 0 4px;
        cursor: pointer;
        &:hover {
          color: #339dff;
          &.del {
            color: #f0153f;
          }
        }
      }
    }
  }
  .time_list {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    min-height: 30px;
    > span {
      margin: 4px 6px;
      line-height: 1;
      white-space: nowrap;
    }
  }
  .table_app_list {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    min-height: 30px;
    .table_app_item {
      margin: 10px;
      .app_top {
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0 auto;
        width: 56px;
        height: 56px;
        border-radius: 6px;
        border: 1px solid #e5e5e5;
        background: #ffffff;
        img {
          width: 38px;
          height: 38px;
        }
      }
      .app_name {
        margin-top: 10px;
        max-width: 100px;
        line-height: 1;
        font-size: 12px;
        text-align: center;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
.bottom_btns {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 16px;
  .primary_btn {
    margin-left: 16px;
  }
}
</style>
