<template>
  <div class="ele-body">
    <el-form ref="form" :model="form" :rules="rules">
      <el-card shadow="never">
        <template v-slot:header>
          <div class="top-search-group">
            <el-input
              placeholder="搜索班次"
              v-model="form.bc"
              clearable
              @input="search"
            />
            <el-button type="primary">搜索</el-button>
          </div>
        </template>
        <el-form-item label="可选班次:" prop="code" style="margin-bottom: 22px">
          <div class="bc-warp">
            <div
              class="item"
              @click="handlselected(item)"
              :style="`background-color:${classesColor[item.id]}`"
              v-for="item in showClassesList"
              :key="item.id"
              >{{ item.name }}</div
            >
            <div
              class="item"
              @click="handlselected(item)"
              :style="`background-color:${classesColor[item.id]}`"
              v-for="item in defaultbtn"
              :key="item.id"
              >{{ item.name }}</div
            >
          </div>
        </el-form-item>
        <el-form-item label="已选班次:" prop="code" style="margin-bottom: 22px">
          <div class="bc-warp">
            <el-tag
              v-for="tag in selectedClasses"
              class="tag"
              :style="`background-color:${classesColor[tag.id]}`"
              :key="tag.name"
              closable
              :type="tag.id"
              @close="handleClose(tag)"
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </el-form-item>
      </el-card>
      <el-card shadow="never">
        <ManagementTable
          ref="ManagementTable"
          :classesColor="classesColor"
          :selectedClasses="selectedClasses"
          @save="save"
          @rest="rest"
        ></ManagementTable>
      </el-card>
    </el-form>
  </div>
</template>
<script>
import {
  getpullDown,
  teamqueuedetailSave,
  getByIdteamqueue,
  teamqueuedetailupdate
} from '@/api/workforceManagement/schedule';
import ManagementTable from './components/ManagementTable.vue';
import { finishPageTab } from '@/utils/page-tab-util';
import { debounce } from 'throttle-debounce';
export default {
  components: {
    ManagementTable
  },
  data() {
    const defaultForm = {
      bc: '',
      checked_bc: ''
    };
    return {
      defaultForm,
      // 表单数据
      form: { ...defaultForm },
      // 表单验证规则
      rules: {},
      type: '', // add/edit
      loading: false,
      colorList: [],
      showClassesList: [],
      classesList: [],
      defaultbtn: [
        {
          name: '休息',
          id: '1'
        },
        {
          name: '清除单元格',
          id: 'clear'
        }
      ],
      selectedClasses: [],
      classesColor: {
        1: '#979d9d',
        clear: '#979d9d'
      },
      addInfo: ''
    };
  },
  computed: {
    title() {
      switch (this.type) {
        case 'add':
          return '排班';
          break;
        case 'edit':
          return '排班';
          break;
        default:
          break;
      }
    }
  },
  async created() {
    this.search = debounce(500, this.search);
    this.init();
    await this.getBc();
    this.configColor();
  },
  methods: {
    // 初始化数据
    init() {
      if (this.$route.query.type) {
        this.type = this.$route.query.type;
        if (this.type == 'add') {
          this.addInfo = this.$store.state.team.addInfo;
          this.setAddinfo();
        } else if (this.type == 'edit') {
          // 按班排班
          let isSchedule = this.$route.query.isSchedule;
          if (isSchedule == '1') {
            this.$nextTick(() => {
              this.$refs.ManagementTable.changanbp();
            });
          }
          this.getByIdteamqueue(this.$route.query.id);
        }
      }
    },
    /* 保存 */
    save() {
      switch (this.type) {
        case 'add':
          this.add();
          break;
        case 'edit':
          this.update();
          break;
        default:
          break;
      }
    },
    // 修改
    update() {
      // 源数据
      let personData = this.$refs.ManagementTable.personData;
      let teamData = this.$refs.ManagementTable.teamData;

      let personDetails = [];
      let teamDetails = [];
      // 处理人员数据
      personData.forEach((n) => {
        // 时间数据
        let teamQueueTime = [];
        for (const [key, value] of Object.entries(n)) {
          if (key !== 'item') {
            teamQueueTime.push({
              date: key,
              teamTimeSimple: value.map((el) => {
                return {
                  id: el.id
                };
              })
            });
          }
        }

        personDetails.push({
          id: n.item.id,
          userId: n.item.userId,
          type: n.item.type,
          teamId: n.item.teamId,
          teamQueueTime
        });
      });
      // 处理班组数据
      teamData.forEach((n) => {
        let teamQueueTime = [];
        for (const [key, value] of Object.entries(n)) {
          if (key !== 'item') {
            teamQueueTime.push({
              date: key,
              teamTimeSimple: value.map((el) => {
                return {
                  id: el.id
                };
              })
            });
          }
        }
        teamDetails.push({
          id: n.item.id,
          type: n.item.type,
          teamId: n.item.teamId,
          teamQueueTime
        });
      });
      let par = {
        id: this.$route.query.id,
        personDetails,
        teamDetails
      };
      const loading = this.$messageLoading('正在请求中..');
      teamqueuedetailupdate(par).then((msg) => {
        this.$message.success(msg);
        this.rest();
      }).finally(() => {
        loading.close();
      })
    },
    // 处理新增信息
    setAddinfo() {
      if (this.addInfo) {
        let addInfo = this.addInfo;
        // 人员数据
        let personDetails = addInfo.personDetails.map((n) => {
          return {
            item: {
              name: n.userName,
              ...n
            }
          };
        });
        // 班组数据
        let teamDetails = addInfo.teamDetails.map((n) => {
          return {
            item: {
              name: n.teamName,
              ...n
            }
          };
        });
        this.$nextTick(() => {
          this.$refs.ManagementTable.setData(personDetails, teamDetails);
        });
      }
    },
    // 新增
    add() {
      let addInfo = this.$store.state.team.addInfo;
      // 源数据
      let personData = this.$refs.ManagementTable.personData;
      let teamData = this.$refs.ManagementTable.teamData;

      let personDetails = [];
      let teamDetails = [];
      // 处理人员数据
      personData.forEach((n) => {
        // 时间数据
        let teamQueueTime = [];
        for (const [key, value] of Object.entries(n)) {
          if (key !== 'item') {
            teamQueueTime.push({
              date: key,
              teamTimeSimple: value.map((el) => {
                return {
                  id: el.id
                };
              })
            });
          }
        }

        personDetails.push({
          userId: n.item.userId,
          type: n.item.type,
          teamId: n.item.teamId,
          teamQueueTime
        });
      });
      // 处理班组数据
      teamData.forEach((n) => {
        let teamQueueTime = [];
        for (const [key, value] of Object.entries(n)) {
          if (key !== 'item') {
            teamQueueTime.push({
              date: key,
              teamTimeSimple: value.map((el) => {
                return {
                  id: el.id
                };
              })
            });
          }
        }
        teamDetails.push({
          type: n.item.type,
          teamId: n.item.teamId,
          

        });
      });
      let par = {
        name: addInfo.name,
        totalPersonNumber: addInfo.totalPersonNumber,
        personDetails,
        teamDetails
      };
      const loading = this.$messageLoading('正在请求中..');
      teamqueuedetailSave(par).then((msg) => {
        this.$message.success(msg);
        finishPageTab();
      }).finally(() => {
        loading.close();
      })
    },
    // 重置
    rest() {
      if (this.type == 'add') {
        this.setAddinfo();
      } else if (this.type == 'edit') {
        this.getByIdteamqueue(this.$route.query.id);
      }
    },
    // 配置颜色
    configColor() {
      this.classesList.forEach((element, index) => {
        this.$set(this.classesColor, element.id, this.colorList[index]);
      });
    },
    handleClose() {
      this.visible = false;
    },
    handlselected(val) {
      if (val.id == '1' || val.id == 'clear') {
        this.selectedClasses = [val];
      } else {
        let result = this.selectedClasses.find((n) => {
          return ['1', 'clear'].includes(n.id);
        });
        if (result) {
          this.selectedClasses = [];
        }
        this.selectedClasses.push(val);
      }
      // 去重
      this.selectedClasses = Array.from(new Set(this.selectedClasses));
    },
    // 删除标签
    handleClose(tag) {
      this.selectedClasses.splice(this.selectedClasses.indexOf(tag), 1);
    },
    // 获取班次
    getBc() {
      return getpullDown().then((res) => {
        this.classesList = res.map((n) => {
          return {
            id: n.id,
            name: `${n.name}(${n.startTime.slice(0, 5)}-${n.endTime.slice(
              0,
              5
            )})`
          };
        });
        const len = Math.round(this.classesList.length/5)
        const color = [
            '#fb6f7b',
            '#f59a23',
            '#4672ca',
            '#2196f3',
            '#00bcd4',
            '#009688',
        ]
        for(var i = 0;i<len;i++){
            this.colorList = this.colorList.concat(color)
        }
        this.showClassesList = this.classesList;
      });
    },
    // 搜索
    search(val) {
      if (val !== '') {
        this.showClassesList = this.classesList.filter((n) => {
          return n.name.toLowerCase().indexOf(val.toLowerCase()) > -1;
        });
      } else {
        this.showClassesList = this.classesList;
      }
    },
    // 获取排班详情
    getByIdteamqueue(id) {
      getByIdteamqueue(id).then((res) => {
        // 回显数据
        //人员数据
        let personDetails = res.personDetails.map((n) => {
          let item = {
            name: n.userName,
            ...n
          };
          delete item.teamQueueTime;
          let teamQueueTime = {};
          if (n.teamQueueTime) {
            n.teamQueueTime.forEach((el) => {
              teamQueueTime[el.date] = el.teamTimeSimple;
            });
          }

          return {
            item,
            ...teamQueueTime
          };
        });
        // 班组数据
        let teamDetails = res.teamDetails.map((n) => {
          let item = {
            name: n.teamName,
            ...n
          };
          delete item.teamQueueTime;
          let teamQueueTime = {};
          if (n.teamQueueTime) {
            n.teamQueueTime.forEach((el) => {
              teamQueueTime[el.date] = el.teamTimeSimple;
            });
          }

          return {
            item,
            ...teamQueueTime
          };
        });
        this.$nextTick(() => {
          this.$refs.ManagementTable.setData(personDetails, teamDetails);
        });
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.location-warp {
  display: flex;
  .detail {
    margin-left: 10px;
  }
}
.top-search-group {
  max-width: 400px;
  display: flex;
  :deep(.el-input input) {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
    border-right-width: 0;
  }
  .el-button {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
}
.bc-warp {
  display: flex;
  flex-wrap:wrap;
  .item {
    height: 34px;
    padding: 0 10px;
    color: #fff;
    border-radius: 4px;
    cursor: pointer;
    margin-right: 10px;
    margin-bottom:10px;
  }
  .item + .item {
    margin-right: 10px;
    margin-bottom:10px;
  }
  .tag {
    color: #fff;
    height: 34px;
    border: none;
    line-height: 34px;
    margin:0 10px 10px 0;
    :deep(.el-tag__close) {
      color: #fff;
    }
  }
}
</style>
