<!-- 换班参数 -->
<template>
  <div>
    <Row justify="center" style="position: relative;" type="flex">
      <Col style="margin-top: 24px;">
        <RadioGroup
          @on-change="changeData"
          size="large"
          style="margin:0px 0px 10px 0px"
          type="button"
          v-if="reciSiteData.length>0"
          v-model="chosenBtn"
        >
          <Radio
            :key="item.wmSiteId"
            :label="index"
            v-for="(item,index) in reciSiteData"
          >{{item.wmName}}</Radio>
        </RadioGroup>

        <Form :label-width="100" :model="formShiftParam" :rules="ruleValidate" ref="formShiftParam">
          <FormItem label="月度换班次数" prop="shiftCounts">
            <InputNumber
              :disabled="inputDisalbed"
              :max="99"
              :min="0"
              placeholder
              style="width:100%"
              v-model="formShiftParam.shiftCounts"
            ></InputNumber>
          </FormItem>
          <FormItem label="换班工时设定" prop="standardTime">
            <Row align="middle" type="flex">
              <Col span="3">
                <FormItem prop="standardTime">
                  <InputNumber
                    :disabled="inputDisalbed"
                    :max="500"
                    :min="0"
                    @on-change="standTimeChange"
                    placeholder="月度标准工时"
                    style="width:100%"
                    v-model="formShiftParam.standardTime"
                  ></InputNumber>
                </FormItem>
              </Col>
              <Col span="1" style="text-align: center">-</Col>
              <Col span="3">
                <FormItem prop="minusTime">
                  <InputNumber
                    :disabled="inputDisalbed"
                    :max="formShiftParam.standardTime>100?100:formShiftParam.standardTime"
                    :min="1"
                    style="width:100%"
                    v-model="formShiftParam.minusTime"
                  ></InputNumber>
                </FormItem>
              </Col>
              <Col span="1" style="text-align: center">≤</Col>
              <Col span="5">
                <span style="text-align:center; display: block;">座席实际排班工时</span>
              </Col>
              <Col span="1" style="text-align: center">≤</Col>
              <Col span="3">
                <FormItem>
                  <InputNumber
                    :disabled="true"
                    :readonly="true"
                    placeholder="月度标准工时"
                    style="width:100%"
                    v-model="formShiftParam.standardTime"
                  ></InputNumber>
                </FormItem>
              </Col>
              <Col span="1" style="text-align: center">+</Col>
              <Col span="3">
                <FormItem prop="plusTime">
                  <InputNumber
                    :disabled="inputDisalbed"
                    :max="100"
                    :min="0"
                    style="width:100%"
                    v-model="formShiftParam.plusTime"
                  ></InputNumber>
                </FormItem>
              </Col>
            </Row>
          </FormItem>
          <!-- <FormItem label="换班审批模式" prop="checkMode">
            <Select :disabled="inputDisalbed" v-model="formShiftParam.checkMode">
              <Option :key="index" :value="index" v-for="(item,index) in checkModeArr">{{ item}}</Option>
            </Select>
          </FormItem> -->
          <FormItem label="不可换班人群">
            <Row type="flex">
              <div
                :style="{background:inputDisalbed?'#f3f3f3':'white',width:'73%'}"
                class="canNotSelectArea"
              >
                <Tag
                  :closable="!inputDisalbed"
                  :key="index"
                  @on-close="handleClose(key)"
                  v-for="(item,key,index) in renderSelectDatas"
                >{{item}}</Tag>
              </div>
              <Button
                :disabled="inputDisalbed"
                @click="showSearchModal"
                style="margin-left:10px;height:32px"
                type="primary"
                v-permission:edit
              >添加</Button>
              <Button
                :disabled="inputDisalbed || renderSelectDatas==={}"
                @click="clearRenderData"
                style="margin-left:10px;height:32px"
                type="primary"
                v-permission:edit
              >清空</Button>
            </Row>
            <Modal
              :mask-closable="false"
              :width="700"
              @on-ok="renderDatas"
              title="不可换班人群"
              v-model="isShowSearch"
            >
              <Row>
                <Col span="6">
                  <Input
                    :data="name"
                    :maxlength="20"
                    placeholder="姓名"
                    style="width:150px;"
                    v-model="userName"
                  ></Input>
                </Col>
                <Col span="6">
                  <Input
                    :data="jobNum"
                    :maxlength="20"
                    placeholder="员工编号"
                    style="width:150px;"
                    v-model="gswEmployeeId"
                  ></Input>
                </Col>
                <Col span="6">
                  <Input :maxlength="20" placeholder="业务小组" style="width:150px;" v-model="teamName"></Input>
                </Col>
                <Col span="2">
                  <Button @click="doInitSearch" type="primary" v-permission:view>查询</Button>
                </Col>
              </Row>
              <br />
              <Table
                :columns="columnsSearch"
                :data="dataListForMolda"
                :loading="searchLoading"
                @on-select="getSelected"
                @on-select-all="selectAll"
                @on-select-all-cancel="cancelAll"
                @on-select-cancel="cancel"
                border
                ref="selection"
              ></Table>
              <Page
                :current.sync="searchForm.pageNum"
                :page-size="searchForm.pageSize"
                :total="total"
                @on-change="pageChange"
                show-total
                style="margin-top:10px"
              />
            </Modal>
          </FormItem>
          <!-- <FormItem label="还班截至日期" prop="deadline">
            <Select :disabled="inputDisalbed" v-model="formShiftParam.deadline">
              <Option :key="index" :value="index" v-for="(item, index) in deadlineArr">{{ item }}</Option>
            </Select>
          </FormItem> -->
          <FormItem label="是否可换班">
            <Row>
              <Col span="4">
                <FormItem prop="canShift">
                  <RadioGroup @on-change="setCanShift" v-model="canShift">
                    <Radio :disabled="inputDisalbed" label="是">是</Radio>
                    <Radio :disabled="inputDisalbed" label="否">否</Radio>
                  </RadioGroup>
                </FormItem>
              </Col>
            </Row>
          </FormItem>
          <FormItem :class="{requireStar:ruleValidate.desc[0].required}" label="不可换班原因" prop="desc">
            <Input
              :autosize="{minRows: 2,maxRows: 5}"
              :disabled="inputDisalbed || formShiftParam.isShift === 1"
              :maxlength="200"
              placeholder
              ref="desc"
              type="textarea"
              v-model="formShiftParam.desc"
            ></Input>
          </FormItem>
          <FormItem>
            <Button
              :disabled="isDisableEditBtn"
              :loading="loading"
              @click="handleSubmit('formShiftParam')"
              type="primary"
              v-permission:edit
            >{{btnName}}</Button>
            <Button
              :disabled="inputDisalbed"
              @click="handleReset('formShiftParam')"
              style="margin-left: 8px"
              v-permission:edit
            >重置</Button>
          </FormItem>
        </Form>
      </Col>
      <Spin fix v-if="spinShow"></Spin>
    </Row>
  </div>
</template>

<script>
import { CHECK_MODE, DEADLINE } from '@conf/dict'
import WmSitesAPI from '@api/common/wmSites'
import WmAgentsAPI from '@api/common/wmAgents'
import ShiftDutyConfigAPI from '@api/common/shiftDutyConfig'
import commonList from '@/mixin/commonList'
import cloneDeep from 'lodash/cloneDeep'

export default {
  name: 'shift-params',
  mixins: [commonList],
  data () {
    return {
      teamName: '',
      btnName: '编辑',
      chosenBtn: 0,
      spinShow: true,
      inputDisalbed: true,
      isDisableEditBtn: true,
      loading: false,
      isShowSearch: false,
      userName: '',
      name: [],
      gswEmployeeId: '',
      checkModeArr: CHECK_MODE,
      deadlineArr: DEADLINE,
      jobNum: [],
      formShiftParam: {
        uid: '',
        shiftCounts: 0,
        isShift: 1,
        remark: '',
        standardTime: 0,
        minusTime: 36,
        plusTime: 20,
        //checkMode: 0,
        //deadline: 0,
        desc: ''
      },
      ruleValidate: {
        shiftCounts: [
          {
            required: true,
            trigger: 'blur',
            type: 'integer',
            min: 0,
            max: 99,
            message: '不能为空,不能超过100'
          }
        ],
        remark: [
          {
            required: true,
            trigger: 'blur',
            message: '不能为空'
          }
        ],
        standardTime: [
          {
            required: true,
            type: 'integer',
            min: 0,
            max: 500,
            message: '必填,不超过500'
          }
        ],
        minusTime: [
          {
            required: true,
            type: 'integer',
            min: 0,
            message: '必填,不超过100'
          }
        ],
        plusTime: [
          {
            required: true,
            type: 'integer',
            min: 0,
            max: 100,
            message: '必填,不超过100'
          }
        ],
        // checkMode: [
        //   {
        //     required: true,
        //     trigger: 'change',
        //     type: 'number',
        //     message: '请选择'
        //   }
        // ],
        // deadline: [
        //   {
        //     required: true,
        //     trigger: 'change',
        //     type: 'number',
        //     message: '请选择'
        //   }
        // ],
        desc: [
          {
            trigger: 'blur',
            type: 'string',
            message: '不可为空'
          }
        ]
      },
      canShift: '否',
      columnsSearch: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '中心',
          key: 'wmSiteName'
        },
        {
          title: '业务小组',
          minWidth: 120,
          key: 'wmTeamName'
        },
        {
          title: '组长',
          render (h, params) {
            return h('div', params.row.map ? params.row.map.leaderName : '')
          }
        },
        {
          title: '座席',
          render (h, params) {
            return h('div', params.row.map ? params.row.map.agentName : '')
          }
        },
        {
          title: '员工编号',
          render (h, params) {
            return h('div', params.row.map ? params.row.map.userCode : '')
          }
        }
      ],
      dataListForMolda: [],
      reciSiteData: [],
      reciShiftData: {},
      selectDatas: {},
      renderSelectDatas: {},
      deepCloneData: {},
      deepCloneTagData: {}
    }
  },
  created () {
    this.btnName = '编辑'
    WmSitesAPI.listOwer().then(({ data }) => {
      if (data.status === 'success') {
        this.reciSiteData = data.data
        this.chosenBtn = 0
        let id = ''
        if (data.data.length > 0) {
          if (data.data[0].wmSiteId !== undefined) {
            id = data.data[0].wmSiteId
            this.isDisableEditBtn = false
            this.queryData(id)
            return
          }
        }
        this.$Message.destroy()
        this.$Message.warning('未查到中心')
        this.spinShow = false
      }
    })
  },
  mounted () {
    this.spinShow = false
  },
  methods: {
    standTimeChange () {
      if (
        this.formShiftParam.standardTime < 100 &&
        this.formShiftParam.minusTime > this.formShiftParam.standardTime
      ) {
        this.formShiftParam.minusTime = 0
      }
    },
    handleClose (key) {
      this.$delete(this.renderSelectDatas, key)
    },
    clearRenderData () {
      this.renderSelectDatas = {}
    },
    renderDatas () {
      for (let key in this.selectDatas) {
        this.renderSelectDatas[key] = this.selectDatas[key].map.agentName
      }
    },
    // 表单提交
    handleSubmit (name) {
      if (!this.inputDisalbed) {
        this.$refs[name].validate(valid => {
          if (valid) {
            //this.loading = true
            if (
              this.reciShiftData.data === undefined ||
              this.reciShiftData.data === null
            ) {
              let datas = this.getData()
              datas.orgCode = this.reciSiteData[this.chosenBtn].wmSiteId
              let siteId = datas.orgCode
              ShiftDutyConfigAPI.add(datas).then(({ data }) => {
                if (data.status === 'success') {
                  this.inputDisalbed = true
                  this.btnName = '编辑'
                  this.loading = false
                  this.$Message.success('数据新增成功')
                  this.queryData(siteId)
                }
              })
            } else {
              let tmpData = this.reciShiftData.data
              let datas = this.getData()
              datas.uuid = tmpData.uuid
              ShiftDutyConfigAPI.edit(datas).then(({ data }) => {
                if (data.status === 'success') {
                  this.inputDisalbed = true
                  this.btnName = '编辑'
                  this.loading = false
                  this.$Message.success('数据修改成功')
                  let siteId = this.reciSiteData[this.chosenBtn].wmSiteId
                  this.queryData(siteId)
                }
              })
            }
          }
        })
      } else {
        this.inputDisalbed = false
        this.btnName = '保存'
      }
    },
    // 表单重置
    handleReset (name) {
      // this.$refs[name].resetFields()
      // this.formShiftParam = this.deepCloneData
      this.formShiftParam = cloneDeep(this.deepCloneData)
      this.renderSelectDatas = cloneDeep(this.deepCloneTagData)
      this.canShift = this.formShiftParam.isShift > 0 ? '是' : '否'
      this.setCanShift(this.canShift)
    },
    // 是否可换班
    setCanShift (label) {
      if (label === '否') {
        this.formShiftParam.isShift = 0
        this.ruleValidate.desc[0].required = true
      } else {
        this.formShiftParam.desc = ''
        this.formShiftParam.isShift = 1
        this.$refs.desc.focus()
        this.ruleValidate.desc[0].required = false
        this.$refs.desc.blur()
      }
    },
    changeData (e) {
      this.queryData(this.reciSiteData[parseInt(e)].wmSiteId)
    },
    queryData (wmSiteId) {
      if (wmSiteId === undefined) {
        this.$Message.destroy()
        return
      }
      this.inputDisalbed = true
      this.btnName = '编辑'
      ShiftDutyConfigAPI.info({ wmSiteId }).then(({ data }) => {
        this.spinShow = false
        if (data.status === 'success') {
          this.reciShiftData = data
          if (data.data === undefined || data.data === null) {
            this.formShiftParam.shiftCounts = 0
            this.formShiftParam.isShift = 1
            this.canShift = '是'
            this.ruleValidate.desc[0].required = false
            this.formShiftParam.standardTime = 0
            this.formShiftParam.minusTime = 0
            this.formShiftParam.plusTime = 0
            // this.formShiftParam.checkMode = 0
            // this.formShiftParam.deadline = 0
            this.formShiftParam.desc = ''
            this.selectDatas = {}
            this.renderSelectDatas = {}
            this.$Message.destroy()
            return
          }

          let temp = data.data
          this.formShiftParam.shiftCounts = temp.shiftNum
          this.formShiftParam.isShift = temp.isShift
          this.canShift = temp.isShift > 0 ? '是' : '否'
          this.ruleValidate.desc[0].required = temp.isShift <= 0
          this.formShiftParam.standardTime = temp.shiftSetBase
          this.formShiftParam.minusTime = temp.shiftSetSubtract
          this.formShiftParam.plusTime = temp.shiftSetAdd
          // this.formShiftParam.checkMode = temp.shiftApprovalModed
          // this.formShiftParam.deadline = temp.shiftEndType
          this.formShiftParam.desc = temp.shiftRemark
          this.deepCloneData = cloneDeep(this.formShiftParam)
          this.initRendSelectDatas(temp.wfmShiftDutyExcept)
          this.$Message.destroy()
        }
      })
    },
    initRendSelectDatas (list) {
      this.renderSelectDatas = {}
      if (list === undefined || list === null || list.length === 0) {
        this.deepCloneTagData = {}
        return
      }

      list.forEach(el => {
        this.renderSelectDatas[el.noShift] = el.map.noShiftName
      })
      this.deepCloneTagData = cloneDeep(this.renderSelectDatas)
    },
    getData () {
      const ids = this.getIds()
      let datas = {
        shiftNum: this.formShiftParam.shiftCounts,
        isShift: this.formShiftParam.isShift,
        shiftSetBase: this.formShiftParam.standardTime,
        shiftSetSubtract: this.formShiftParam.minusTime,
        shiftSetAdd: this.formShiftParam.plusTime,
        // shiftApprovalModed: this.formShiftParam.checkMode,
        // shiftEndType: this.formShiftParam.deadline,
        shiftRemark: this.formShiftParam.desc,
        map: {
          codeExcept: ids
        }
      }
      return datas
    },
    doSearch () {
      this.searchLoading = true
      if (this.reciSiteData.length < 1) {
        return
      }

      this.dataListForMolda = []
      this.searchForm.siteid = this.reciSiteData[this.chosenBtn].wmSiteId
      this.searchForm.gswEmployeeId = this.gswEmployeeId.trim()
      this.searchForm.teamName = this.teamName.trim()
      this.searchForm.userName = this.userName.trim()
      this.$nextTick(() => {
        WmAgentsAPI.listOwer({ ...this.searchForm })
          .then(({ data }) => {
            this.searchLoading = false
            if (data.status === 'success') {
              this.dataListForMolda = data.data.list
              this.total = data.data.total
              this.$nextTick(() => {
                let tmp = this.$refs.selection.$refs.tbody.objData
                for (let key in tmp) {
                  let id = tmp[key].map.userId
                  if (id !== undefined && id !== '' && id !== null) {
                    if (this.selectDatas[id]) {
                      tmp[key]._isChecked = true
                    } else {
                      tmp[key]._isChecked = false
                    }
                  }
                }
              })
            }
          })
          .catch(() => {
            this.searchLoading = false
          })
        this.searchForm.gswEmployeeId = ''
        this.searchForm.userName = ''
        this.searchForm.username = ''
      })
    },
    showSearchModal () {
      this.isShowSearch = true
      this.selectDatas = {}
      this.gswEmployeeId = ''
      this.userName = ''
      this.teamName = ''
      this.doInitSearch()
    },
    getSelected (data, row) {
      this.selectDatas[row.map.userId] = row
    },
    cancel (data, row) {
      delete this.selectDatas[row.map.userId]
    },
    selectAll (data) {
      data.forEach(element => {
        let id = element.map.userId
        if (id !== undefined && id !== '' && id !== null) {
          this.selectDatas[id] = element
        }
      })
    },
    cancelAll (data) {
      let tmp = this.$refs.selection.$refs.tbody.objData
      for (let key in tmp) {
        let id = tmp[key].map.userId
        if (id !== undefined && id !== '' && id !== null) {
          delete this.selectDatas[id]
        }
      }
    },
    getIds () {
      let datas = this.renderSelectDatas
      let ids = ''
      for (let key in datas) {
        let id = key
        if (id !== undefined && id !== '' && id !== null) {
          ids = ids + id + ';'
        }
      }
      ids = ids.substring(0, ids.length - 1)
      return ids
    }
  }
}
</script>

<style lang="less">
.canNotSelectArea {
  min-height: 32px;
  border: 1px solid #dcdee2;
  max-height: 200px;
  overflow-y: auto;
  border-radius: 4px;
}

.requireStar .ivu-form-item-label:before {
  content: '*';
  display: inline-block;
  margin-right: 4px;
  line-height: 1;
  font-family: SimSun;
  font-size: 12px;
  color: #ed4014;
}
</style>
