<template>
  <div>
    <LxHeader
      icon="md-apps"
      :text="$route.meta.title"
      style="margin-bottom: 10px; border: 0px; margin-top: 15px"
      text="快速调令"
    >
      <template #content>
        <Button type="primary" style="width: 120px;" @click="$emit('normalCreate')">普通调令</Button>
        <Button type="primary" style="width: 120px;" @click="add">添加</Button>
      </template>
    </LxHeader>

    <div class="content">
      <Table :columns="columns" :data="data" stripe></Table>
    </div>

    <div class="btn">
      <Button type="primary" ghost long style="max-width: 260px;margin-right: 40px;" @click="data = []">清空</Button>
      <Button type="primary" long style="max-width: 260px;" @click="submit">提交</Button>
    </div>
  </div>
</template>

<script>
import { uuid } from "@/utils";
import { index, save } from "@/api/system/baseForm";
import LxHeader from "@/components/LxHeader";
export default {
  components: {
    LxHeader
  },
  props: {
    equipments: Array
  },
  data() {
    return {
      form: {
        no: '',
        equipment_id: '',
        start_time: '',
        end_time: '',
        content: '',
        level: 1,
        status: 1
      },
      columns: [
        {
          type: 'index',
          width: 50,
          title: ' '
        },
        {
          title: '点位',
          width: 160,
          key: 'equipment_id',
          align: 'center',
          render: (h,{ row }) => {
            return h('Select',{
              props: {
                value: row.equipment_id,
                filterable: true,
                size: 'small',
                transfer: true
              },
              on: {
                ['on-select']:e => {
                  row.equipment_id = e.value;
                }
              }
            },this.equipments.map(i => {
              return h('Option',{
                props: {
                  value: i.id,
                }
              },i.name)
            }))
          }
        },
        {
          title: '开启时间',
          width: 140,
          align: 'center',
          key: 'start_time',
          render: (h,{ row }) => {
            return h('TimePicker',{
              props: {
                value: row.start_time,
                type: 'time',
                size: 'small',
                transfer: true
              },
              on: {
                ['on-change']:e => row.start_time = e
              }
            })
          }
        },
        {
          title: '结束时间',
          width: 140,
          align: 'center',
          key: 'end_time',
          render: (h,{ row }) => {
            return h('TimePicker',{
              props: {
                value: row.end_time,
                type: 'time',
                size: 'small',
                transfer: true
              },
              on: {
                ['on-change']:e => row.end_time = e
              }
            })
          }
        },
        {
          title: '调令内容',
          minWidth: 200,
          key: 'content',
          render: (h,{ row }) => {
            return h('Input',{
              props: {
                size: 'small',
                value: row.content
              },
              on: {
                ['input']:e => row.content = e
              }
            })
          }
        },
        {
          title: '操作',
          width: 140,
          key: 'operate',
          render: (h,{ row, index }) => {
            return h('Poptip',{
              props: {
                title: '确认要删除吗？',
                confirm: true,
                transfer: true
              },
              on: {
                ['on-ok']:e => {
                  this.data.splice(index,1)
                }
              }
            },[
              h('Button',{
                props: {
                  type: 'primary',
                  size: 'small'
                }
              },'删除')
            ])
          }
        }
      ],
      data: []
    }
  },
  methods: {
    isTimeFormat (str) {
      let regex = /^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;
      return regex.test(str);
    },

    add () {
      this.$prompt('请输入内容','快速调令',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        closeOnClickModal: false,
        inputPlaceholder: '点位 开始时间 结束时间 调令内容,\n点位 开始时间 结束时间 调令内容 \n每个值以空格隔开，每条调令用","分割',
        beforeClose:(action, instance, done) => {
          if (action === 'confirm') {
            let value = instance._data.inputValue;
            try {
              let group = value.split(/,|，/).map(i => i.replace(/\n/g,''));
              group.forEach((item,index) => {
                let dataArr = item.split(/\s+/);
                if (!this.equipments.find(i => i.name === dataArr[0])) {
                  throw new Error('未找到该点位');
                }
                if (!(this.isTimeFormat(dataArr[1]) && this.isTimeFormat(dataArr[2]))) {
                  throw new Error('时间格式有误');
                }
              })
              done();
            } catch (err) {
              this.$message({
                type: 'warning',
                message: /^TypeError./.test(err) ? '数据格式有误' : err
              })
            }
          } else {
            done();
          }
        },
      }).then(({ value, action }) => {
        if (action === 'confirm') {
          let uid = uuid();
          let group = value.split(',').map(i => i.replace(/\n/g,''));
          group.forEach((item,index) => {
            let dataArr = item.split(/\s+/);
            this.data.push({
              no: uid,
              equipment_id: this.equipments.find(i => i.name === dataArr[0])?.id,
              start_time: `${dataArr[1]}`,
              end_time: `${dataArr[2]}`,
              content: dataArr[3] || '',
              level: 1,
              status: 1
            })
          })
          console.log(this.data)
        }
      }).catch(_ => {})
    },

    submit () {
      console.log(this.data)
      let promiseAll = this.data.map(form => {
        return save({
          table_name: 'transfers',
          ...form,
          start_time: `${this.$moment().format('YYYY-MM-DD')} ${form.start_time}`,
          end_time: `${this.$moment().format('YYYY-MM-DD')} ${form.end_time}`,
        },false)
      })
      let loadingInstance = this.$loading({
        lock:true,
        background:"rgba(0,0,0,0.4)",
        text:"正在加载中..."
      })
      Promise.all(promiseAll).then(res => {
        this.data = [];
        loadingInstance.close();
        this.$message({
          type: 'success',
          message: '添加成功'
        })
      }).catch(_ => {
        loadingInstance.close()
      })
    }
  },
  computed: {},
}
</script>

<style scoped lang="scss">
.btn {
  display: flex;
  justify-content: center;

  margin-top: 20px;
}
</style>
<style>
.el-message-box__input .el-textarea .el-textarea__inner {
  min-height: 120px !important;
}
</style>
