<template>
  <el-dialog
    :title="!dataForm.id ? '新建' : '编辑'"
    :close-on-click-modal="false"
    append-to-body
    :visible.sync="visible"
    class="JNPF-dialog JNPF-dialog_center"
    lock-scroll
    width="1000px"
  >
    <el-row :gutter="15" class="">
      <el-form ref="formRef" :model="dataForm" :rules="dataRule" size="small" label-width="120px" label-position="right"   >
        <template v-if="!loading">
          <!-- 具体表单 -->
          <el-col :span="12">
            <jnpf-form-tip-item label="倒班类型" prop="chgClassType">
              <JnpfSelect v-model="dataForm.chgClassType" placeholder="请选择倒班类型" clearable  :options="chgClassTypeOptions" :props="chgClassTypeProps" > </JnpfSelect>
            </jnpf-form-tip-item>
          </el-col>
          <el-col :span="24">
            <jnpf-form-tip-item label-width="0">
              <div class="JNPF-common-title">
                <h2>班次明细</h2>
              </div>
              <el-table :data="dataForm.shiftConfigEntityList" size="mini">
                <el-table-column type="index" width="50" label="序号" align="center" />

                <el-table-column label="班组" prop="classGroup" align="center">
                  <template slot-scope="scope">
                    <JnpfSelect v-model="scope.row.classGroup" placeholder="请选择" clearable :options="classGroupOptions" :props="classGroupProps"> </JnpfSelect>
                  </template>
                </el-table-column>
                <el-table-column label="班次" prop="classRate" align="center">
                  <template slot-scope="scope">
                    <JnpfSelect v-model="scope.row.classRate" placeholder="请选择" clearable :options="classRateOptions" :props="classRateProps"> </JnpfSelect>
                  </template>
                </el-table-column>
                <el-table-column label="开始时间" prop="bgnDtime" align="center">
                  <template slot-scope="scope">

                  <JnpfTimePicker v-model="scope.row.bgnDtime"
                                    :startTime="time(false, 1, 1, '', 'HH:mm', '')"
                                    :endTime="time(false, 1, 1, '', 'HH:mm', '')" placeholder="请选择开始时间" clearable
                                    :style='{ "width": "100%" }' format="HH:mm">
                    </JnpfTimePicker>
                    </template>
                </el-table-column>
                <el-table-column label="结束时间" prop="endDtime" align="center">
                  <template slot-scope="scope">
                <JnpfTimePicker v-model="scope.row.endDtime"
                                    :startTime="time(false, 1, 1, '', 'HH:mm', '')"
                                    :endTime="time(false, 1, 1, '', 'HH:mm', '')" placeholder="请选择结束时间" clearable
                                    :style='{ "width": "100%" }' format="HH:mm">
                    </JnpfTimePicker>
            </template>
        </el-table-column>
                <el-table-column label="序列号" prop="seqNo" align="center">
                  <template slot-scope="scope">
                    <JnpfInput
                      v-model="scope.row.seqNo"
                      placeholder="请输入"
                      clearable
                      min="0"
                      type="number"
                      :style="{ width: '100%' }"
                    >
                    </JnpfInput>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="50">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" class="JNPF-table-delBtn" @click="delShiftConfigEntityList(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="table-actions" @click="addShiftConfigEntityList()">
                <el-button type="text" icon="el-icon-plus">添加</el-button>
              </div>
            </jnpf-form-tip-item>
          </el-col>
          <!-- 表单结束 -->
        </template>
      </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer">

       <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading"> 确 定</el-button>
      <el-button @click="visible = false"> 取 消</el-button>

    </span>
  </el-dialog>
</template>


<script>
  import request from '@/utils/request'
  import { mapGetters } from 'vuex'
  import { getDataInterfaceRes } from '@/api/systemData/dataInterface'
  import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
  import { getDefaultCurrentValueUserId } from '@/api/permission/user'
  import { getDefaultCurrentValueDepartmentId } from '@/api/permission/organize'
  import { getDateDay, getLaterData, getBeforeData, getBeforeTime, getLaterTime } from '@/components/Generator/utils/index.js'
  import { thousandsFormat } from '@/components/Generator/utils/index'
  import { getFieldDataSelect } from '@/api/onlineDev/visualDev'
  export default {
    components: {},
    props: [],
    data() {
      return {

        selectedData: [],
        selectedIds: [],
        list: [],
        innerValue: '',
        listQuery: {
          keyword: '',
          currentPage: 1,
          pageSize: 20,

        },
        total: 0,
        checked: '',
        checkedTxt: '',
        checkedRow: {},
        listLoading: false,
        inputHovering: false,
        itemVisible: false,
        detailVisible: false,
        multiple: true,
        dataFormSubmitType: 0,
        continueBtnLoading: false,
        index: 0,
        prevDis: false,
        nextDis: false,
        allList: [],
        visible: false,
        loading: false,
        btnLoading: false,
        formRef: 'formRef',
        setting: {},
        eventType: '',
        userBoxVisible: false,
        selectDialogVisible: false,
        currTableConf: {},
        dataValueAll: {},
        addTableConf: {
          qa_scheme_base_twList: {
            popupType: 'dialog',
            hasPage: true,
            popupTitle: '选择数据',
            pageSize: 20,
            columnOptions: [],
            interfaceId: '',
            interfaceName: '',
            relationOptions: [],
            templateJson: [],
            popupWidth: '800px',
          },
        },
        //可选范围默认值
        ableAll: {},
        tableRows: {
          qa_scheme_base_twList: {
            itemId: '',
            itemIdOptions: [],
            unit: '',
            unitOptions: [],
            standardValue: '',
            standardValueOptions: [],
            upperLimit: '',
            upperLimitOptions: [],
            lowerLimit: '',
            lowerLimitOptions: [],
            remark: '',
            remarkOptions: [],
            enabledmark: undefined,
          },
        },
        Vmodel: '',
        currVmodel: '',
        dataForm: {
          chgClassType: undefined,
          shiftConfigEntityList: []
        },
        chgClassTypeOptions: [
          { fullName: '四班三倒', id: '1' },
          { fullName: '三班两到', id: '2' },
        ],
        chgClassTypeProps: { label: 'fullName', value: 'id' },
        classGroupOptions: [
          { fullName: '甲', id: '甲' },
          { fullName: '乙', id: '乙' },
          { fullName: '丙', id: '丙' },
          { fullName: '丁', id: '丁' },
        ],
        classGroupProps: { label: 'fullName', value: 'id' },
        classRateOptions: [
          { fullName: '白', id: '1' },
          { fullName: '中', id: '2' },
          { fullName: '夜', id: '3' },
        ],
        classRateProps: { label: 'fullName', value: 'id' },
        tableRequiredData: {},
        dataRule: {
          chgClassType: [
            {
              required: true,
              message: '请选择倒班类型',
              trigger: 'change',
            },
          ],
        },


        childIndex: -1,
        isEdit: false,
        interfaceRes: {
          schemeNo: [],
          schemeName: [],
          schemeType: [],
          remark: [],
          creatorUserId: [],
          creatorTime: [],
          qa_scheme_base_twitemId: [],
          qa_scheme_base_twunit: [],
          qa_scheme_base_twstandardValue: [],
          qa_scheme_base_twupperLimit: [],
          qa_scheme_base_twlowerLimit: [],
          qa_scheme_base_twremark: [],
        },
      }
    },
    computed: {
      ...mapGetters(['userInfo']),
    },
    watch: {},
    created() {
      this.dataAll()
      this.initDefaultData()
      this.dataValueAll = JSON.parse(JSON.stringify(this.dataForm))
      this.initData()
    },
    mounted() {},
    methods: {

      search() {
        this.listQuery.currentPage = 1
        this.listQuery.pageSize = this.pageSize
        this.initData()
      },
      reset() {
        this.listQuery.keyword = ''
        this.listQuery.currentPage = 1
        this.listQuery.pageSize = this.pageSize
        this.initData()
      },



      select() {
        let newArr = this.selectedData.filter(o => {
          return this.dataForm.qa_scheme_base_twList.every(item => {
            return o.id !== item.itemId
          })
        })
        newArr.forEach(o => {
          let item = {
            itemId: o.id,
            itemName:o.itemName,
            unit: o.unitName,
            standardValue: undefined,
            upperLimit: undefined,
            lowerLimit: undefined,
            remark: undefined,
            printMergeYn:"N",
            printItem:undefined,
          }
          this.getqa_scheme_base_twList(item)
        })
        this.initDefaultData()
        this.itemVisible = false
      },

      rowClick(row) {
        this.checked = row.id
        this.checkedTxt = row[this.relationField]
        this.checkedRow = row
      },
      prev() {
        this.initDefaultData()
        this.index--
        if (this.index === 0) {
          this.prevDis = true
        }
        this.nextDis = false
        for (let index = 0; index < this.allList.length; index++) {
          const element = this.allList[index]
          if (this.index == index) {
            this.getInfo(element.id)
          }
        }
      },
      next() {
        this.initDefaultData()
        this.index++
        if (this.index === this.allList.length - 1) {
          this.nextDis = true
        }
        this.prevDis = false
        for (let index = 0; index < this.allList.length; index++) {
          const element = this.allList[index]
          if (this.index == index) {
            this.getInfo(element.id)
          }
        }
      },

      goBack() {
        this.visible = false
        this.$emit('refreshDataList', true)
      },


      dataAll() {


      },



      clearData() {
        this.dataForm = JSON.parse(JSON.stringify(this.dataValueAll))
      },
      init(id, isDetail, allList) {
        this.prevDis = false
        this.nextDis = false
        this.allList = allList || []
        if (allList.length) {
          this.index = this.allList.findIndex(item => item.id === id)
          if (this.index == 0) {
            this.prevDis = true
          }
          if (this.index == this.allList.length - 1) {
            this.nextDis = true
          }
        } else {
          this.prevDis = true
          this.nextDis = true
        }
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          if (this.dataForm.id) {
            this.loading = true
            request({
              url: '/api/example/Qa_scheme_base/' + this.dataForm.id,
              method: 'get',
            }).then(res => {
              this.dataInfo(res.data)
              this.loading = false
            })
          } else {
            this.clearData()
            this.initDefaultData()
          }
        })
        this.$store.commit('generator/UPDATE_RELATION_DATA', {})
      },
      //初始化默认数据
      initDefaultData() {

      },
      // 表单提交
      dataFormSubmit(type) {
        this.dataFormSubmitType = type ? type : 0
        this.$refs['formRef'].validate(valid => {
          if (valid) {
            this.request()
          }
        })
      },
      request() {
        let _data = this.dataList()
        if (this.dataFormSubmitType == 2) {
          this.continueBtnLoading = true
        } else {
          this.btnLoading = true
        }
        if (!this.dataForm.id) {
          request({
            url: '/api/example/shiftConfig',
            method: 'post',
            data: _data,
          })
            .then(res => {
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 1000,
                onClose: () => {
                  if (this.dataFormSubmitType == 2) {
                    this.$nextTick(() => {
                      this.clearData()
                      this.initDefaultData()
                    })
                    this.continueBtnLoading = false
                    return
                  }
                  this.visible = false
                  this.btnLoading = false
                  this.$emit('refresh', true)
                },
              })
            })
            .catch(() => {
              this.btnLoading = false
              this.continueBtnLoading = false
            })
        } else {
          request({
            url: '/api/example/Qa_scheme_base/' + this.dataForm.id,
            method: 'PUT',
            data: _data,
          })
            .then(res => {
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 1000,
                onClose: () => {
                  if (this.dataFormSubmitType == 2) return (this.continueBtnLoading = false)
                  this.visible = false
                  this.btnLoading = false
                  this.$emit('refresh', true)
                },
              })
            })
            .catch(() => {
              this.btnLoading = false
              this.continueBtnLoading = false
            })
        }
        console.log('########## >>>> ' + this.visible)
      },

      delShiftConfigEntityList(index) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          type: 'warning',
        })
            .then(() => {
              this.dataForm.shiftConfigEntityList.splice(index, 1)
            })
            .catch(() => {
            })
      },
      addShiftConfigEntityList() {
        let item = {
          classGroup: undefined,
          classRate: undefined,
          bgnDtime: undefined,
          endDtime: undefined,
          seqNo: undefined
        }
        this.dataForm.shiftConfigEntityList.push(item)
      },
      getqa_scheme_base_twList(value) {
        let item = { ...this.tableRows.qa_scheme_base_twList, ...value }
        this.dataForm.qa_scheme_base_twList.push(item)
        this.childIndex = this.dataForm.qa_scheme_base_twList.length - 1
        this.isEdit = true
        this.isEdit = false
        this.childIndex = -1
      },
      openSelectDialog(key) {
        this.currTableConf = this.addTableConf[key]
        this.currVmodel = key
        this.selectDialogVisible = true
        this.$nextTick(() => {
          this.$refs.selectDialog.init()
        })
      },
      addForSelect(data) {
        for (let i = 0; i < data.length; i++) {
          let t = data[i]
          if (this['get' + this.currVmodel]) {
            this['get' + this.currVmodel](t)
          }
        }
      },
      dateTime(timeRule, timeType, timeTarget, timeValueData, dataValue) {
        let timeDataValue = null
        let timeValue = Number(timeValueData)
        if (timeRule) {
          if (timeType == 1) {
            timeDataValue = timeValue
          } else if (timeType == 2) {
            timeDataValue = dataValue
          } else if (timeType == 3) {
            timeDataValue = new Date().getTime()
          } else if (timeType == 4) {
            let previousDate = ''
            if (timeTarget == 1 || timeTarget == 2) {
              previousDate = getDateDay(timeTarget, timeType, timeValue)
              timeDataValue = new Date(previousDate).getTime()
            } else if (timeTarget == 3) {
              previousDate = getBeforeData(timeValue)
              timeDataValue = new Date(previousDate).getTime()
            } else {
              timeDataValue = getBeforeTime(timeTarget, timeValue).getTime()
            }
          } else if (timeType == 5) {
            let previousDate = ''
            if (timeTarget == 1 || timeTarget == 2) {
              previousDate = getDateDay(timeTarget, timeType, timeValue)
              timeDataValue = new Date(previousDate).getTime()
            } else if (timeTarget == 3) {
              previousDate = getLaterData(timeValue)
              timeDataValue = new Date(previousDate).getTime()
            } else {
              timeDataValue = getLaterTime(timeTarget, timeValue).getTime()
            }
          }
        }
        return timeDataValue
      },
      time(timeRule, timeType, timeTarget, timeValue, formatType, dataValue) {
        let format = formatType == 'HH:mm' ? 'HH:mm:00' : formatType
        let timeDataValue = null
        if (timeRule) {
          if (timeType == 1) {
            timeDataValue = timeValue || '00:00:00'
            if (timeDataValue.split(':').length == 3) {
              timeDataValue = timeDataValue
            } else {
              timeDataValue = timeDataValue + ':00'
            }
          } else if (timeType == 2) {
            timeDataValue = dataValue
          } else if (timeType == 3) {
            timeDataValue = this.jnpf.toDate(new Date(), format)
          } else if (timeType == 4) {
            let previousDate = ''
            previousDate = getBeforeTime(timeTarget, timeValue)
            timeDataValue = this.jnpf.toDate(previousDate, format)
          } else if (timeType == 5) {
            let previousDate = ''
            previousDate = getLaterTime(timeTarget, timeValue)
            timeDataValue = this.jnpf.toDate(previousDate, format)
          }
        }
        return timeDataValue
      },
      dataList() {
        var _data = this.dataForm
        return _data
      },
      dataInfo(dataAll) {
        let _dataAll = dataAll
        this.dataForm = _dataAll
        this.isEdit = true
        this.dataAll()
        for (let i = 0; i < _dataAll.qa_scheme_base_twList.length; i++) {
          this.childIndex = i
          this.selectedIds.push(_dataAll.qa_scheme_base_twList[i].itemId)
        }
        this.childIndex = -1
      },
    },
  }
</script>
