<template>
  <div style="padding-bottom: 45px;">
    <Steps :current="step" size="small" class="steps">
      <Step title="点位选择"></Step>
      <Step title="调令创建"></Step>
      <Step title="完成"></Step>
    </Steps>

    <Card style="margin-top: 8px;" dis-hover v-show="step === 0">
      <div class="select">
        <div class="select-item">
          <div class="select-item__title">选择范围</div>
          <el-checkbox border
                       size="mini"
                       :indeterminate="isIndeterminateArea"
                       v-model="isSelectAllArea"
                       @change="handleAreaCheckAll">全选</el-checkbox>
          <el-checkbox-group size="mini"
                             :value="select.filter[2].value.split(',').map(i => Number(i))"
                             @input="e => select.filter[2].value = e.filter(i=>i).toString()"
                             @change="handleAreaCheck">
            <el-checkbox border v-for="item in areas" :label="item.value">{{
                item.key
              }}</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="select-item">
          <div class="select-item__title">选择泵闸</div>
          <el-checkbox border
                       size="mini"
                       :indeterminate="isIndeterminateType"
                       v-model="isSelectAllType"
                       @change="handleTypeCheckAll">全选</el-checkbox>
          <el-checkbox-group size="mini"
                             :value="select.filter[1].value.split(',').map(i => Number(i))"
                             @input="e => select.filter[1].value = e.filter(i=>i).toString()"
                             @change="handleTypeCheck">
            <el-checkbox border v-for="item in types" :label="item.value">{{
                item.key
              }}</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="select-item">
          <div class="select-item__title">名称</div>
          <el-input size="mini" v-model="select.name" placeholder="请输入名称"></el-input>
        </div>
      </div>

      <div class="picked-list">
        <Tag v-for="item in pickedEquipments"
             :key="item.id"
             type="dot"
             closable
             color="primary"
             @on-close="closeTag(item)">{{ item.name }}</Tag>
      </div>

      <div class="equipment-list">
        <Table stripe
               :loading="loading"
               size="small"
               :data="equipments"
               :columns="table"
               @on-row-click="row => equipmentSelect(pickedEquipments, row, false)"
               @on-select="(selection, row) => equipmentSelect(selection, row, false)"
               @on-select-cancel="(selection, row) => equipmentSelect(selection, row, false)"
               @on-select-all="(selection) => equipmentSelect(selection, {}, true)"
               @on-select-all-cancel="(selection) => equipmentSelect(selection, {}, true)"></Table>

        <div class="page">
          <Page :total="total"
                :page-size="select.page_size"
                @on-change="e => {
                select.page = e;
                getEquipments()
              }"/>
        </div>
      </div>
    </Card>

    <Card style="margin-top: 8px;" dis-hover v-show="step === 1">
      <div class="select">
        <div class="select-item">
          <div class="select-item__title">日期选择</div>
          <el-input size="small"
                    :value="date"
                    readonly
                    @focus="isShowDatePicker = true"></el-input>
        </div>
      </div>

      <div v-for="(item, index) in form" :key="index">
        <Divider />
        <div>
          <h3>{{ ++index }}.{{ item._name }}</h3>
          <Button size="small" type="primary" @click="item._isShow = !item._isShow">{{ item._isShow ? '收起' : '展开' }}</Button>
        </div>
        <transition name="fade">
          <el-form size="mini"
                   v-show="item._isShow"
                   :model="item"
                   label-position="top">
            <el-form-item label="闸门数量">
              <el-input-number v-model="item.kaiqishuliang" :precision="0" :max="Number(item._bengzhashuliang)" :min="0"></el-input-number>
            </el-form-item>
            <el-form-item label="水泵数量">
              <el-input-number v-model="item.kaiqishuliang1" :precision="0" :max="Number(item._shuibengtaishu)" :min="0"></el-input-number>
            </el-form-item>
            <el-form-item label="调令类型">
              <el-radio-group v-model="item.diaolingleixing">
                <el-radio :label="i.value" v-for="i in diaolingleixing">{{ i.key }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="开启时间">
              <el-time-select v-model="item.start_time"
                              :picker-options="{ start: '00:00', step: '00:05', end: '23:59' }"
                              @change="startTimePick(item)"></el-time-select>
            </el-form-item>
            <el-form-item label="持续时间">
              <el-input-number v-model="item._last"
                               :precision="1"
                               :min="0"
                               :step="0.5"
                               @change="lastTimePick(item)"></el-input-number>
            </el-form-item>
            <el-form-item label="结束时间">
              <el-time-select v-model="item.end_time"
                              :picker-options="{ start: '00:00', step: '00:05', end: '23:59', minTime: item.start_time }"></el-time-select>
            </el-form-item>
            <el-form-item label="调令内容">
              <el-input v-model="item.content" type="textarea" :autosize="{ minRows: 2 }"></el-input>
            </el-form-item>
            <el-form-item label="调令等级">
              <el-radio-group v-model="item.level">
                <el-radio :label="i.value" v-for="i in [{ label: '一般', value: 1 },{ label: '紧急', value: 2 }]">{{ i.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </transition>
      </div>
    </Card>

    <div class="btns">
      <Button v-show="step === 1" ghost size="default" type="primary" @click="forwardStep">上一步</Button>
      <Button size="default" type="primary" @click="nextStep">下一步</Button>
    </div>

    <transition name="fade">
      <div v-show="isShowDatePicker" class="datepicker">
        <div class="mask" @click="isShowDatePicker = false"></div>
        <DatePicker ref="datepicker"
                    class="datepicker-cpn"
                    is-expanded
                    :model-config="config"
                    :rows="2"
                    v-model="date"></DatePicker>
      </div>
    </transition>
  </div>
</template>

<script>
import Calendar from "v-calendar/src/components/Calendar.vue";
import DatePicker from "v-calendar/src/components/DatePicker.vue";
import { show } from "@/api/system/customFormField";
import {index, save} from "@/api/system/baseForm";
import {uuid} from "@/utils";
import {checkTransfer} from "@/api/other";

export default {
  components: {
    DatePicker,
    Calendar
  },
  data() {
    return {
      config: {
        type: 'string',
        mask: 'YYYY-MM-DD'
      },
      isShowDatePicker: false,
      step: 0,

      isIndeterminateArea: false,
      areas: [],
      isSelectAllArea: false,
      isIndeterminateType: false,
      types: [],
      isSelectAllType: false,
      select: {
        page: 1,
        page_size: 20,
        table_name: 'equipments',
        filter: [
          {
            key: "name",
            op: "like",
            value: ""
          },
          {
            key: "type",
            op: "in",
            value: ""
          },
          {
            key: "area",
            op: "in",
            value: ""
          }
        ]
      },
      diaolingleixing: [],

      loading: false,
      total: 0,
      equipments: [],
      table: [
        {
          type: 'selection',
          width: 54,
          align: 'center'
        },
        {
          key: "name",
          title: "名称"
        },
        {
          key: "area",
          title: "区域",
          render: (h,{ row }) => h('span', this.areas.find(i => i.value === row.area)?.key)
        },
      ],

      pickedEquipments: [],
      form: [],
      date: "",
    }
  },
  methods: {
    startTimePick (row) {
      if (row._last) {
        const [hour, min] = row.start_time
          .split(":")
          .map((i) => Number(i));
        let addTime = {
          hour: Math.floor(row._last),
          min: (row._last % 1) * 60,
        };
        let resTime = {
          hour:
            hour + addTime.hour + (min + addTime.min >= 60 ? 1 : 0),
          min: (min + addTime.min) % 60,
        };
        row.end_time = `${resTime.hour
          .toString()
          .padStart(2, "0")}:${resTime.min
          .toString()
          .padStart(2, "0")}`;
      }
    },
    lastTimePick (row) {
      const [hour, min] = row.start_time
        .split(":")
        .map((i) => Number(i));
      let addTime = {
        hour: Math.floor(row._last),
        min: (row._last % 1) * 60,
      };
      let resTime = {
        hour:
          hour + addTime.hour + (min + addTime.min >= 60 ? 1 : 0),
        min: (min + addTime.min) % 60,
      };
      row.end_time = `${resTime.hour
        .toString()
        .padStart(2, "0")}:${resTime.min
        .toString()
        .padStart(2, "0")}`;
    },

    handleAreaCheckAll (e) {
      this.select.filter[2].value = e ? this.areas.map(i => i.value).toString() : "";
      this.isIndeterminateArea = false;

      this.select.page = 1;
      this.getEquipments();
    },
    handleAreaCheck (e) {
      let count = e.length;
      this.isSelectAllArea = count === this.areas.length;
      this.isIndeterminateArea = count > 0 && count < this.areas.length;

      this.select.page = 1;
      this.getEquipments();
    },
    handleTypeCheckAll (e) {
      this.select.filter[1].value = e ? this.types.map(i => i.value).toString() : "";
      this.isIndeterminateType = false;

      this.select.page = 1;
      this.getEquipments();
    },
    handleTypeCheck (e) {
      let count = e.length;
      this.isSelectAllType = count === this.types.length;
      this.isIndeterminateType = count > 0 && count < this.types.length;

      this.select.page = 1;
      this.getEquipments();
    },

    closeTag (row) {
      let findIndex = this.pickedEquipments.findIndex(i => i.id === row.id)
      this.pickedEquipments.splice(findIndex, 1)
    },
    equipmentSelect (selection, row, isAll) {
      if (!isAll) {
        let findIndex = this.pickedEquipments.findIndex(i => i.id === row.id)
        if (findIndex === -1) {
          this.pickedEquipments.push(row)
        } else {
          this.pickedEquipments.splice(findIndex, 1)
        }
      } else {
        if (selection.length === this.equipments.length) {
          selection.forEach(myrow => {
            let findIndex = this.pickedEquipments.findIndex(i => i.id === myrow.id)
            if (findIndex === -1) {
              this.pickedEquipments.push(myrow)
            } else {
              this.pickedEquipments.splice(findIndex, 1)
            }
          })
        } else {
          this.equipments.forEach(myrow => {
            let findIndex = this.pickedEquipments.findIndex(i => i.id === myrow.id)
            this.pickedEquipments.splice(findIndex, 1)
          })
        }
      }
    },

    async getArea() {
      const obj = (await show({ id: 4 }, false))?.select_item;
      if (obj && typeof obj === "object") {
        let keys = Object.keys(obj);
        if (keys.length > 0) {
          this.areas = keys.map((key) => {
            return {
              key,
              value: /^\d*$/.test(obj[key]) ? Number(obj[key]) : obj[key],
            };
          });
        }
      }
    },
    async getType() {
      const obj = (await show({ id: 1 }, false))?.select_item;
      if (obj && typeof obj === "object") {
        let keys = Object.keys(obj);
        if (keys.length > 0) {
          this.types = keys.map((key) => {
            return {
              key,
              value: /^\d*$/.test(obj[key]) ? Number(obj[key]) : obj[key],
            };
          });
        }
      }
    },
    async getDiaolingleixing() {
      const obj = {
        "逻辑调令": "4",
        "防汛调令": "2",
        "水环境调令": "1",
        "船只过闸调令": "3"
      };
      if (obj && typeof obj === "object") {
        let keys = Object.keys(obj);
        if (keys.length > 0) {
          this.diaolingleixing = keys.map((key) => {
            return {
              key,
              value: /^\d*$/.test(obj[key]) ? Number(obj[key]) : obj[key],
            };
          });
        }
      }
    },


    async getEquipments () {
      this.loading = true
      try {
        const res = await index(this.select,false)
        this.total = res.total;
        this.equipments = res.data.map(i => ({
          ...i,
          _checked: !!this.pickedEquipments.find(j => j.id === i.id)
        }));
        this.loading = false;
      } catch (err) {
        this.loading = false;
      }
    },


    forwardStep () {
      if (this.step === 1) {
        this.step--;
      }
    },
    nextStep () {
      if (this.step === 0) {
        if (this.pickedEquipments.length <= 0) {
          alert("请先选择泵闸")
          return
        }
        this.form = this.pickedEquipments.map(i => ({
          equipment_id: i.id,
          start_time: "",
          _last: 0,
          end_time: "",
          content: "",
          level: 1,
          kaiqishuliang: 0,
          _bengzhashuliang: i.bengzhashuliang,
          kaiqishuliang1: 0,
          _shuibengtaishu: i.shuibengtaishu,
          _name: i.name,
          leibie: "",
          _isShow: true,
        }))
        this.step++;
      }
    },


    async submit() {
      const submitData = this.form.filter(
        (i) => i.start_time || i.end_time || i.content
      );

      let isNeed = 0;
      try {
        await this.$confirm("是否需要走流程？","提示",{
          confirmButtonText: "需要",
          cancelButtonText: "不需要",
          type: "info",
          closeOnClickModal: false,
          distinguishCancelAndClose: true
        })
        isNeed = 1;
      } catch (e) {
        if (e === 'cancel') {
          isNeed = 0;
        } else {
          return
        }
      }

      const uid = uuid();
      let promiseAll = [];
      let loadingInstance = this.$loading({
        lock: true,
        background: "rgba(0,0,0,0.4)",
        text: "正在加载中...",
      });
      for (let j = 0;j < submitData.length;j++) {
        let i = submitData[j]

        delete i["equipment_id-span"];
        delete i["_index"];
        delete i["_rowKey"];

        i.start_time = `${this.date} ${i.start_time}`;
        i.end_time = i.end_time ? `${this.date} ${i.end_time}` : '';
        i.no = uid;
        i.status = 1;

        try {
          const res = await checkTransfer({
            start_time: i.start_time,
            end_time: i.end_time,
            equipment_id: i.equipment_id,
            diaolingleixing: i.diaolingleixing
          })
          promiseAll.push(
            save(
              {
                table_name: "transfers",
                ...i,
                shifouzouliucheng: isNeed,
                is_adjust: -1
              },
              false
            )
          );
        } catch (e) {

        }
      }
      Promise.all(promiseAll)
        .then((res) => {
          loadingInstance.close();
          this.$message({
            type: "success",
            message: `成功创建${res.length}条调令`,
          });
        })
        .catch((_) => {
          loadingInstance.close();
        });
    },
  },
  computed: {},
  watch: {
    pickedEquipments (newVal) {
      this.equipments = this.equipments.map(i => ({
        ...i,
        _checked: !!this.pickedEquipments.find(j => j.id === i.id)
      }));
    }
  },
  created() {
    this.getArea();
    this.getType();
    this.getEquipments();
    this.getDiaolingleixing();
  },
}
</script>

<style scoped lang="scss">
.steps {
  border: 1px solid #dcdee2;
  margin-top: 8px;
  background: #fff;
  border-radius: 4px;
  padding: 10px 0 6px 10px;
}

.select {
  &-item {
    &__title {
      font-weight: 600;
      line-height: 2;
    }
  }
}

.equipment-list {
  margin-top: 10px;
  .page {
    display: flex;
    justify-content: center;
    margin-top: 10px;
  }
}
.btns {
  z-index: 10;
  padding: 6px 10px;
  filter: drop-shadow(0 -2px 4px #0001);
  background: #fff;
  position: fixed;
  bottom: 0;
  width: 100%;
  left: 0;
}
.datepicker {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;

  z-index: 99999997;

  .mask {
    position: absolute;
    width: 100%;
    top: 0;
    left: 0;
    height: 100%;
    z-index: 99999998;
    background: #0002;
  }
  &-cpn {
    position: absolute;
    width: 100%;
    bottom: 0;
    z-index: 999999999;
  }
}
h3 {
  text-align: center;
  color: $primaryColor;
  line-height: 2;
}
@media (max-width: 768px) {
  ::v-deep .el-checkbox {
    margin-right: 0;
    margin-bottom: 4px;
  }
  ::v-deep .el-checkbox.is-bordered.el-checkbox--mini {
    padding: 3px 8px 3px 8px;
  }
  ::v-deep .el-checkbox.is-bordered.el-checkbox--mini .el-checkbox__label {
    padding-left: 6px;
  }
  ::v-deep .ivu-table-small td {
    height: 36px;
  }
  ::v-deep .el-form-item--mini .el-form-item__label {
    line-height: 1.5;
    padding-bottom: 6px;
  }
  ::v-deep .el-form-item--mini.el-form-item {
    margin-bottom: 10px;
  }
}
</style>
