<template>
  <div>
    <Modal :value="isShow" title="排班" width="48" @on-visible-change="e => $emit('update:isShow',e)">
      <template v-slot:default>
        <el-form ref="elForm" :model="form" :rules="rules" label-width="110px">
          <el-form-item label="时间选择" prop="end_time">
            <div style="font-weight: 600">{{ date }}</div>
            <el-time-picker
              size="small"
              value-format="HH:mm:ss"
              v-model="form.start_time"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }"
              placeholder="开始时间"
             @change="startTimePick">
            </el-time-picker>
            <el-time-picker
              size="small"
              value-format="HH:mm:ss"
              v-model="form.end_time"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }"
              placeholder="结束时间"
              @change="endTimePick">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="护工选择" prop="nurse_id">
            <el-select v-model="form.nurse_id"
                       placeholder="请选择护工"
                       style="width: 300px;"
                       filterable remote
                       :remote-method="remoteNurse"
                       v-load-more="nurseLoad"
                       :loading="loading">
              <el-option v-for="(item,index) in nurses" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上门地址选择" prop="address_id">
            <el-select v-model="form.address_id" placeholder="请选择上门地址选择" style="width: 300px;">
              <el-option v-for="(item,index) in addresses" :label="item.address" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="服务项目" prop="schedule_list_skus">
            <xy-table
              ref="table"
              :height="200"
              :is-page="false"
              :list="skus"
              :table-item="skuTable"
              @select="skuSelect"
              @select-all="skuSelect">
              <template v-slot:btns><div></div></template>
            </xy-table>
<!--            <el-checkbox-group v-model="form.schedule_list_skus">-->
<!--              <template v-for="(item) in skus">-->
<!--                <el-checkbox :label="item.sku.id">{{ item.sku.name }}</el-checkbox>-->
<!--              </template>-->
<!--              <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAllChange">全选</el-checkbox>-->
<!--            </el-checkbox-group>-->
          </el-form-item>
        </el-form>
      </template>

      <template v-slot:footer>
        <Poptip
          :transfer="true"
          confirm
          title="确认要删除吗"
          @on-ok="destroySchedule">
          <Button type="primary" ghost>删除</Button>
        </Poptip>
        <Button @click="$emit('update:isShow',false)" style="margin-left: 8px">取消</Button>
        <Button type="primary" @click="submit">确认</Button>
      </template>
    </Modal>
  </div>
</template>

<script>
import {getList as getWorker} from '@/api/worker'
import {parseTime} from '@/utils'
import {scheduleDelete, scheduleSave} from '@/api/schedule'

export default {
  props: {
    customerId: [Number, String],
    orderId: [Number, String],
    productId: [Number, String],
    date: {
      type: String,
      default: ''
    },
    isShow: {
      type: Boolean,
      default: false
    },
    skus: {
      type: Array,
      default: () => []
    },
    addresses:{
      type:Array,
      default:()=>[]
    }
  },
  data() {
    return {
      nurses:[],
      nurseSelect:{
        page:1,
        page_size:10,
        keyword:''
      },
      loading:false,
      checkAll:true,
      indeterminate:false,
      form: {
        id:'',
        customer_id: '',
        product_id: '',
        order_id: '',
        nurse_id: '',
        address_id:'',
        start_time: '',
        end_time: '',
        schedule_list_skus: []
      },
      rules: {
        nurse_id: [
          {required: true, message: '请选择护工'}
        ],
        start_time: [
          {required: true, message: '请选择开始时间'}
        ],
        end_time: [
          {required: true, message: '请选择结束时间'}
        ],
        address_id: [
          {required: true, message: '请选择护工'}
        ],
        schedule_list_skus: [
          {required: true, message: '请选择护理项目'}
        ]
      },

      skuTable:[
        {
          type:'selection',
          width:43
        },
        {
          prop:'sku.name',
          width: 100,
          label:'姓名',
          sortable:false
        },
        {
          label:'服务时长(分)',
          prop:'sku.time_lenth',
          width: 124,
          sortable: false
        },
        {
          label:'内容',
          prop:'sku.service',
          minWidth:140,
          sortable: false,
          align:'left'
        }
      ]
    }
  },
  methods: {
    nurseLoad(){
      this.nurseSelect.page ++
      this.getNurses()
    },
    async getNurses(){
      let res = await getWorker(this.nurseSelect,false)
      if(res.data.length === 0){
        this.nurseSelect.page --
        this.$message({
          type: 'warning',
          message: '没有更多护工了'
        })
        return
      }
      this.nurses.push(...res.data)
    },

    async remoteNurse(e){
      this.nurses = []
      this.nurseSelect.keyword = e
      this.nurseSelect.page = 1
      await this.getNurses()
    },

    startTimePick(e){
      this.form.start_time = `${this.date} ${e}`
      console.log(this.form)
    },
    endTimePick(e){
      this.form.end_time = `${this.date} ${e}`
      console.log(this.form)
    },

    // handleCheckAllChange(val){
    //   this.form.schedule_list_skus = val ? this.skus.map(item => {
    //     return item.sku.id
    //   }) : []
    //   this.indeterminate =! this.indeterminate
    // },
    skuSelect(selection){
      this.form.schedule_list_skus = selection.map(item => {
        return item.sku.id
      })
    },
    toggleRow(ids=[]){
      this.skus.forEach(item => {
        if(ids.indexOf(item.sku_id) !== -1){
          this.$refs['table'].toggleRowSelection(item)
        }
      })
    },
    toggleAll(){
      this.skus.forEach(item => {
        this.$refs['table'].toggleRowSelection(item)
      })

      this.form.schedule_list_skus = this.skus.map(item => {
        return item.sku_id
      })
    },

    submit() {
      this.form.customer_id = this.customerId
      this.form.product_id = this.productId
      this.form.order_id = this.orderId
      let temp = this.form.schedule_list_skus.map(item => {
        return {sku_id: item}
      })
      this.form.schedule_list_skus = temp
      this.$refs['elForm'].validate().then(valid => {
        console.log(valid)
        if (valid) {
          scheduleSave(this.form).then(res => {
            this.$successMessage('add', '排班')
            this.$emit('update:isShow', false)
            this.$emit('refresh')
          }).catch(err => {
            this.$emit('update:isShow', false)
          })
        }
      })
    },
    destroySchedule(){
      scheduleDelete({id:this.form.id}).then(res => {
        this.$successMessage('destroy','排班')
        this.isShow = false
        this.$emit('refresh')
      })
    },
  },
  watch: {
    isShow(val) {
      if (val) {
        this.form.address_id = this.addresses.filter(item => {
          return item.default === 1
        })[0]?.id || ''

        //默认选择
        if(this.form.schedule_list_skus.length > 0){
          this.toggleRow(this.form.schedule_list_skus)
        }else{
          this.toggleAll()
        }

      } else {
        this.$emit('update:date','')
        this.$refs['elForm'].resetFields()
        this.$refs['table'].clearSelection()
        console.log(this.form)
      }
    }
  },
  mounted() {
    this.getNurses()
  }
}
</script>

<style lang="scss" scoped>

::v-deep .el-form-item__error {
  transform: none !important;
  left: 0 !important;
}
</style>
