<template>
  <a-modal
    title="指派维修员"
    style="top: 20px;"
    :width="1200"
    v-model="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
  >
    <a-form :form="form">
      <a-form-item style="display:none">
        <a-input v-decorator="['id']" />
      </a-form-item>

      <a-row>
        <a-col :span="10">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="所属分类">
            <a-select v-decorator="['typeId', {rules: [{ required: true, message: '请选择所属分类' }]}]"
                      @change="selectDevice">
              <a-select-option v-for="item in typeList" :key="item.id" :value="item.id">{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="报修设备">
            <a-select v-decorator="['deviceId', {rules: [{ required: true, message: '请选择所属设备' }]}]"
                      @change="getDeviceName">
              <a-select-option v-for="item in deviceList" :key="item.id" :value="item.id">{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="10">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="报修人">
            <a-input placeholder="报修人"
                     v-decorator="['name', {rules: [{ required: true, message: '请选择报修人' }]}]" />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="联系电话">
            <a-input placeholder="联系电话"
                     v-decorator="['phone', {rules: [{ required: true, message: '请输入联系电话' }]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="10">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="维修负责人">
            <a-select v-decorator="['repairUserId']"
                      @change="selectUser">
              <a-select-option v-for="item in userList" :key="item.userId">{{ item.userName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="报修地点">
            <a-select v-decorator="['addressId', {rules: [{ required: true, message: '请选择报修地点' }]}]"
                      @change="selectRoomList">
              <a-select-option v-for="item in addressList" :key="item.id" :value="item.id">{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="10">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="楼层">
            <a-select v-decorator="['floorId', {rules: [{ required: true, message: '请选择详细地址' }]}]"
                      @change="selectFloorName">
              <a-select-option v-for="item in roomList" :key="item.id" :value="item.id">{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="门牌号(地点)">
            <a-input placeholder="门牌号"
                     v-decorator="['room' ]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="10">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="故障类型">
            <a-select v-decorator="['failureTypeId' ]"
            >
              <a-select-option v-for="item in failureTypeList" :key="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="故障描述">
            <a-textarea placeholder="故障描述" v-decorator="['explain']" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="10">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="报修图片">
            <a-upload
              v-decorator="['repairImages']"
              list-type="picture-card"
              class="avatar-uploader"
              :file-list="fileList"
              :action="uploadUrl"
              :headers="headers"
              @preview="handlePreview"
              @change="handleChangeFileList"
            >
              <div v-if="fileList.length < 4">
                <a-icon type="plus" />
                <div class="ant-upload-text"> 上传</div>
              </div>
            </a-upload>
            <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
              <img style="width: 100%" :src="previewImage" />
            </a-modal>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<script>
import { review } from '@/api/admin/repair'
import pick from 'lodash.pick'
import { getUserList } from '@/api/system'
import { getRepairTypeList, selectWorkerIdByTypeId } from '@/api/admin/repair/repairDeviceType'
import { getRepairDeviceList } from '@/api/admin/repair/repairDevice'
import { getRepairFailureTypeList } from '@/api/admin/repair/repairFailureType'

import { getRepairAddressList } from '@/api/admin/repair/repairAddress'
import { getRepairRoomList } from '@/api/admin/repair/repairAddressFloor'

import moment from 'moment'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const dateFormat = 'YYYY-MM-DD HH:mm:ss'

export default {
  name: 'RepairModal',
  props: {},
  components: {},
  data () {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      uploadUrl: process.env.VUE_APP_API_BASE_URL + '/admin/repairAttach/upload?operate=repair',
      imageUrl: '',
      headers: {
        Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
      },
      fileList: [],
      confirmLoading: false,
      mdl: {},
      workerData: [],
      // 开始日期
      beginDate: null,
      // 结束日期
      endDate: null,
      dateValue: [],
      previewVisible: false,
      previewImage: '',
      form: this.$form.createForm(this),
      typeList: [],
      deviceList: [],
      failureTypeList: [],
      userList: [],
      addressList: [],
      roomList: [],
      typeName: '',
      typeId: '',
      deviceName: '',
      deviceId: '',
      floor: '',
      floorId: '',
      address: '',
      addressId: '',
      files: []
    }
  },
  beforeCreate () {
  },
  created () {
    this.selectType()
    this.selectFailureType()
    this.getRepairAddressList()
  },
  methods: {
    moment,
    selectType () {
      getRepairTypeList().then(res => {
        this.typeList = res.rows
      })
    },
    selectUser (id) {
    },
    // 根据分类id 查询对应设备
    selectDevice (typeId) {
      let type = this.typeList.find(item => item.id == typeId)
      this.typeId = type.id
      this.typeName = type.name
      getRepairDeviceList({
        typeId
      }).then(res => {
        this.deviceList = res.rows
      })
      selectWorkerIdByTypeId({ typeId }).then(res => {
        this.userList = res.data
        this.userList = this.userList.map(item => {
          item.repairUserId = item.userId
          return item
        })
      })
    },
    getDeviceName (deviceId) {
      let device = this.deviceList.find(item => item.id == deviceId)
      console.log(device)
      this.deviceName = device.label
      this.deviceId = device.key
    },
    selectFailureType () {
      getRepairFailureTypeList().then(res => {
        this.failureTypeList = res.rows
      })
    },
    getRepairAddressList () {
      getRepairAddressList().then(res => {
        this.addressList = res.rows
      })
    },

    selectRoomList (roomId) {
      console.log('selectRoomList', roomId)
      let room = this.addressList.find(item => item.id == roomId)
      getRepairRoomList({ 'addressId': roomId }).then(res => {
        this.roomList = res.rows
      })
      this.address = room.label
      this.addressId = room.key
    },
    selectFloorName (floorId) {
      let floor = this.roomList.find(item => item.id == floorId)

      this.floor = floor.label
      this.floorId = floor.key
    },

    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64FileList(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleCancel () {
      this.previewVisible = false
    },
    // 上传banner
    handleChangeFileList ({ fileList }) {
      fileList.forEach(item => {
        if (item.response !== undefined) {
          this.files.push(item.response.id)
        }
      })
      this.fileList = fileList
    },
    add () {
      this.form.resetFields()
      this.mdl.repairImages = null
      this.edit({ id: 0 })
    },
    edit (record) {
      console.log(record)
      if (record.id !== 0) {
        this.selectDevice(record.typeId)
        this.selectRoomList(record.addressId)
      }

      this.mdl = Object.assign(record)
      this.mdl.typeList = this.typeList

      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'sn', 'repairName', 'typeList', 'repairLevel', 'typeId', 'typeName', 'deviceId', 'deviceName',
          'name', 'phone', 'addressId', 'address', 'floorId', 'floor', 'repairUserId', 'room', 'explain', 'perUserId', 'perUserName', 'preDate', 'cause',
          'solution', 'failureTypeId', 'failureTypeName'))
      })
    },
    onChange (dates, dateStrings) {
      console.log('From: ', dateStrings[0], ', to: ', dateStrings[1])
      this.beginDate = dateStrings[0]
      this.endDate = dateStrings[1]
      this.dateValue = [moment(this.beginDate, dateFormat), moment(this.endDate, dateFormat)]
    },
    handleSubmit (e) {
      e.preventDefault()
      console.log(this.files)

      const uniqueArr = this.files.filter((value, index, self) => {
        return self.indexOf(value) === index
      })
      console.log()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.confirmLoading = true
          values.beginDate = this.beginDate
          values.endDate = this.endDate
          values.typeName = this.typeName
          values.typeId = this.typeId
          values.deviceName = this.deviceName
          values.deviceId = this.deviceId
          values.floor = this.floor
          values.floorId = this.floorId
          values.address = this.address
          values.addressId = this.addressId
          const repairImages = []
          this.fileList.forEach((file, index) => {
            // 添加原来的
            if (file.hasOwnProperty('name') && file.hasOwnProperty('url') && file.hasOwnProperty('uid')) {
              repairImages.push({ 'name': file.name, 'url': file.name, 'uid': index })
            }
            if (file.status === 'done' && file.response.code === 0) {
              const data = file.response
              repairImages.push({ 'name': data.fileName, 'url': data.fileName, 'uid': index })
            }
          })
          // 多个图片
          values.repairImages = JSON.stringify(repairImages)
          review(values, uniqueArr).then(res => {
            if (res.code === 0) {
              this.$message.success('保存成功')
              this.$emit('ok')
              this.visible = false
            } else {
              this.$message.error(res.msg)
            }
          }).catch(() => {
            this.$message.error('系统错误，请稍后再试')
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  },
  watch: {}
}

function getBase64 (img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
</script>
