<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-12-17 09:40:42
 * @LastEditors  : 无尘
 * @LastEditTime : 2019-12-26 16:15:05
 -->

<!--
<cycle-set
  :rangeShow="rangeShow"
  :attenceGroupData="attenceGroupData"
  :attenceGroupId="attenceGroupId"
  @hideCycleDialog="hideCycleDialog">
</cycle-set>

import cycleSet from '@/components/app/dailyAttendance/cycle-set.vue'
 -->

<template>
  <el-dialog class="edit-dialog" title="选择班次" :visible.sync="customDialog" width="600px" :before-close="handleClose">
    <div class="edit-dialog-body">
      <el-form :model="ruleFormData" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="周期名称：" prop="rangeName">
          <limitInput :inputWidth="305" :inputValue.sync="ruleFormData.rangeName" :holder="'请输入周期名称'" :getByType="'word'" :maxLength="6"> </limitInput>
        </el-form-item>
        <el-form-item label="每个周期天数：" prop="">
          <div>
            <el-input-number v-model="ruleFormData.days" controls-position="right" @change="handleRangeDay" :step="1" :step-strictly="true" :min="3" :max="31"></el-input-number>
            <span class="font-12 color-909399">以{{ ruleFormData.days }}天为周期进行循环，最大周期天数为31天</span>
          </div>

          <div class="range-classes">
            <ul>
              <li v-for="(item, index) in ruleFormData.classes" :key="index + 'class'">
                <span>第{{ index + 1 }}天：</span>
                <el-select v-model="item.classesId" placeholder="请选择" @change="changeClass($event, item)">
                  <el-option v-for="item in tableData" :key="item.classesId" :label="'班次' + item.classesName + item.label" :value="item.classesId"> </el-option>
                </el-select>
              </li>
            </ul>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click.stop="customCancel">取消</el-button>
      <el-button type="primary" @click.stop="customConfirm('ruleForm')">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import limitInput from '@/components/limit-input.vue';
import { getRequest } from '@/api/api';
import errMsg from '@/common/js/error';
import showMsg from '@/common/js/showmsg';
import { _debounce } from '@/common/js/public';
export default {
  name: 'cycle-set',
  components: { limitInput },
  props: {
    rangeShow: {
      type: Boolean,
      default: false
    },
    attenceGroupId: {
      type: String,
      default: ''
    },
    classesJson: {
      type: [Array, Object],
      default() {
        return [];
      }
    },
    attenceGroupData: {
      type: [Array, Object],
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      enterpriseId: JSON.parse(sessionStorage.getItem('userInfos')).enterpriseId,
      selClassesId: this.attenceGroupId,
      customDialog: false,
      tableData: [],
      classesName: '',
      ruleFormData: {
        classesRangeId: '',
        days: 3,
        rangeName: '',
        classes: [
          {
            classesId: '',
            classesName: ''
          },
          {
            classesId: '',
            classesName: ''
          },
          {
            classesId: '',
            classesName: ''
          }
        ]
      },
      rules: {
        rangeName: [{ required: true, message: '请输入周期名称', trigger: 'blur' }]
      }
    };
  },
  methods: {
    /**
     * 修改班次
     */
    changeClass(e, item) {
      const that = this;
      that.tableData.forEach(ele => {
        if (ele.classesId == e) {
          item.classesName = ele.classesName;
        }
      });
    },
    /**
     * 修改周期
     */
    handleRangeDay(e) {
      const that = this;
      const length = !!that.ruleFormData.classes ? that.ruleFormData.classes.length : 0;
      if (e - length > 0) {
        for (let index = 0; index < e - length; index++) {
          that.ruleFormData.classes.push({
            classesId: '',
            classesName: ''
          });
        }
      }

      if (e - length < 0) {
        // console.log(e, length, length - e);
        that.ruleFormData.classes.splice(e - 1, length - e);
      }
    },
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      that.getClassifyData();
    }, 500),
    // 搜索清除
    clearInput() {
      const that = this;
      that.currentPage = 1;
      that.getClassifyData();
    },
    customConfirm: _debounce(async function(formName) {
      const that = this;
      let flag = true;
      that.ruleFormData.classes.forEach(ele => {
        flag = !ele.classesId ? false : true;
      });
      if (!flag) {
        showMsg.showmsg('请选择班次', 'warning');
        return false;
      }
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.customDialog = false;
          that.$emit('hideCycleDialog', that.ruleFormData);
          that.resetData();
        }
      });
    }, 300),
    resetData() {
      const that = this;
      that.$nextTick(() => {
        that.ruleFormData = {
          classesRangeId: '',
          days: 3,
          rangeName: '',
          classes: [
            {
              classesId: '',
              classesName: ''
            },
            {
              classesId: '',
              classesName: ''
            },
            {
              classesId: '',
              classesName: ''
            }
          ]
        };
      });
    },
    /**
     *   关闭
     */
    handleClose(done) {
      const that = this;
      done();
      that.hideDialog();
    },

    /**
     *  取消
     */
    customCancel() {
      const that = this;
      that.hideDialog();
    },
    /**
     * 隐藏弹出层
     */
    hideDialog() {
      const that = this;
      that.customDialog = false;
      that.$emit('hideCycleDialog');
      that.resetData();
    },
    /**
     * 获取班次
     */
    getClassifyData() {
      const that = this;
      if (that.classesJson && that.classesJson.length) {
        that.classesJson.forEach(ele => {
          ele.label = ' ';
          if (!!ele.classessTimesJson && ele.classessTimesJson.length) {
            ele.classessTimesJson.forEach(child => {
              ele.label += child.startTime + '-' + child.endTime;
            });
          }
        });
      }
      that.tableData = that.classesJson || [];
      /* let para = {
        attenceGroupId: that.$route.query.attenceGroupId,
        enterpriseId: that.enterpriseId
      };
      getRequest('/haoban-app-attence-web/attence-classes-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (resData.result && resData.result.length) {
              resData.result.forEach(ele => {
                if (ele.classessTimesJson) {
                  ele.classessTimesJson = JSON.parse(ele.classessTimesJson);
                }
              });
              resData.result.forEach(ele => {
                ele.label = ' ';
                if (!!ele.classessTimesJson && ele.classessTimesJson.length) {
                  ele.classessTimesJson.forEach(child => {
                    ele.label += child.startTime + '-' + child.endTime;
                  });
                }
              });
            }
            that.tableData = resData.result || [];
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        }); */
    },
    /**
     * 获取周期
     */
    getRangeData() {
      const that = this;
      let para = {
        enterpriseId: that.enterpriseId,
        attenceGroupId: that.attenceGroupId
      };
      getRequest('/haoban-app-attence-web/attence-range-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result && !!resData.result.length) {
              resData.result.forEach(ele => {
                ele.classes = ele.classesList;
              });
              that.ruleFormData = resData.result[0] || [];
            }
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    rangeShow: function(newData, oldData) {
      const that = this;
      that.customDialog = newData;
    },
    attenceGroupId(newData) {
      const that = this;
      if (newData) {
        that.getRangeData();
      }
    },
    attenceGroupData(newData) {
      const that = this;
      if (Object.keys(newData).length) {
        that.ruleFormData = JSON.parse(JSON.stringify(newData));
      }
    },
    classesJson(newData) {
      const that = this;
      if (newData.length) {
        that.getClassifyData();
      }
    }
  },
  mounted() {
    const that = this;
    if (that.attenceGroupId) {
      that.getRangeData();
    }
    if (Object.keys(that.attenceGroupData).length) {
      that.ruleFormData = JSON.parse(JSON.stringify(that.attenceGroupData));
    }
    if (that.classesJson.length) {
      that.getClassifyData();
    }
    that.customDialog = that.rangeShow;
  }
};
</script>
<style lang="scss" scoped>
.range-classes {
  margin-top: 20px;
  padding: 10px 19px;
  background: rgba(247, 248, 250, 1);
  li {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
