<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-input placeholder="工单名称" v-decorator="['repairName', {rules: [{ required: true, message: '请输入工单名称' }]}]"/>
          </a-form-item>
        </a-col>
        <a-col :span='10'>

          <a-form-item label='故障时间' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-date-picker
              format='YYYY-MM-DD HH:mm:ss'
              valueFormat='YYYY-MM-DD HH:mm:ss'
              v-decorator="['failureDate',{rules: [{ required: true, message: '选择报修时间'}]}]"
              :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
              type='date'
              placeholder='选择报修时间'
              style='width: 100%;'

            />
          </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="['repairLevel',{rules: [{ required: true, message: '请选择故障等级'}]}]"
                      placeholder='请选择故障等级'>
              <a-select-option value='一级'>
                一级
              </a-select-option>
              <a-select-option value="二级">
                二级
              </a-select-option>
              <a-select-option value='三级'>
                三级
              </a-select-option>
              <a-select-option value='四级'>
                四级
              </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="['failureTypeId', {rules: [{ required: true, message: '请选择所属设备' }]}]"
            >
              <a-select-option v-for="item in failureTypeList" :key="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="['typeId', {rules: [{ required: true, message: '请选择所属分类' }]}]"
                      @change="selectDevice">
              <a-select-option v-for="item in typeList" :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-select v-decorator="['repairDevice', {rules: [{ required: true, message: '请选择所属设备' }]}]"
            >
              <a-select-option v-for="item in deviceList" :key="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="['userId', {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="['workerId', {rules: [{ required: true, message: '请输入维修负责人' }]}]"
            >
              <a-select-option v-for="item in userList" :key="item.id">{{ 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">{{ 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="['roomId', {rules: [{ required: true, message: '请选择详细地址' }]}]"
            >
              <a-select-option v-for="item in roomList" :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-input placeholder="门牌号" v-decorator="['area', {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-textarea placeholder="报修内容" v-decorator="['content']"/>
          </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', {rules: [{ required: true, message: '上传室内图片' }]}]"
              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,selectWorkerIdByTypeId } from '@/api/admin/repair'
import pick from 'lodash.pick'
import { getUserList } from '@/api/system'
import {getRepairTypeList} from '@/api/admin/repair/repairType'
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/repairRoom'


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 + '/api/dfs/upload',
      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: []
    }
  },
  beforeCreate () {
  },
  created () {
    // 工人列表
    // getUserList({ dtype: 'Admin' }).then(res => {
    //   if (res.code === 0) {
    //     const result = res.rows
    //     result.forEach(r => {
    //       this.workerData.push({ value: r.id, text: r.username + '(' + r.mobile + ')' })
    //     })
    //   }
    // })
    this.selectType()
    this.selectFailureType()
    this.getRepairAddressList()
  },
  methods: {
    moment,
    selectType () {
      getRepairTypeList().then(res => {
        this.typeList = res.rows
      })
    },
    // 根据分类id 查询对应设备
    selectDevice(id){
      getRepairDeviceList({"typeId":id}).then(res =>{
        this.deviceList = res.rows
      })
      selectWorkerIdByTypeId({"typeId":id}).then(res =>{
        this.userList =res.data
      })
    },
    selectFailureType(){
      getRepairFailureTypeList().then(res =>{
        this.failureTypeList = res.rows
      })
    },
    getRepairAddressList(){
      getRepairAddressList().then(res =>{
        this.addressList = res.rows
      })
    },

    selectRoomList(id){
      getRepairRoomList({"addressId":id}).then(res =>{
        this.roomList = res.rows
      })
    },


    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 }) {
      this.fileList = fileList
    },
    add () {
      this.form.resetFields()
      this.mdl.repairImages = null
      this.edit({ id: 0 })
    },
    edit (record) {
      this.mdl = Object.assign(record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'repairImages', 'workerId', 'repairMateriel'))
      })
      // 处理日期
      if (this.mdl.beginDate !== null && this.mdl.beginDate !== undefined && this.mdl.endDate !== null && this.mdl.endDate !== undefined) {
        this.dateValue = [moment(this.mdl.beginDate, dateFormat), moment(this.mdl.endDate, dateFormat)]
      }
      // 图片
      if (this.mdl.repairImages) {
        console.log("1111111111111111111111")
        this.mdl.repairImages = JSON.parse(this.mdl.repairImages)
        this.mdl.repairImages.forEach((item, i) => {
          item.url = process.env.VUE_APP_API_BASE_URL + item.url
        })
        this.fileList = this.mdl.repairImages
      } else {
        this.fileList = []
      }
    },
    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()
      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

          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).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>
