<template>
  <div class="col-sm-12" style="margin: 20px 0px;">
    <data-grid :model="model" v-ref:grid class="list_area table_sy" style="padding: 0px">
      <template partial='head'>
        <tr>
          <th class="textNoLineBreak">序号</th>
          <th class="textNoLineBreak">编号</th>
          <th class="textNoLineBreak">设备数</th>
          <th class="textNoLineBreak">
            <button
              type="button"
              class="btn btn-info head-but"
              @click="$parent.$parent.openDevicesModal()"
              v-if="false"
              :disabled="$parent.$parent.mark === 1"
            >添加</button>
          </th>
        </tr>
      </template>
      <template partial='body'>
        <tr>
          <td style="text-align: center;">
            <nobr>{{$index+1}}</nobr>
          </td>
          <td style="text-align: center;">
            <nobr>{{row.f_userinfo_id}}</nobr>
          </td>
          <td style="text-align: center;">
            <nobr>{{row.amount}}</nobr>
          </td>
          <td style="text-align: center;">
            <nobr>
              <button
                type="button"
                name="button"
                class="btn btn-link"
                @click="$parent.$parent.openDevicesModal(row)"
              >
                {{$parent.$parent.mark === 1 ? '查看' : '修正'}}
              </button>
              <button
                type="button" name="button" class="btn btn-link"
                @click="$parent.$parent.deleteUserinfo(row)"
                v-if="$parent.$parent.showDeleteUserInfo"
                :disabled="$parent.$parent.mark === 1"
              >
                删除
              </button>
            </nobr>
          </td>
        </tr>
      </template>
    </data-grid>


    <modal v-if="showDevices" :show.sync="showDevices" v-ref:modal :large="true" :backdrop="false" title="表具设备信息">
      <header slot="modal-header" class="modal-header">
        <button type="button" class="close" @click="closeDevices"><span>&times;</span></button>
        <h4 class="modal-title">表具设备信息</h4>
      </header>
      <article slot="modal-body" class="modal-body clearfix">
        <div v-for="(i, item) in devicesinfo" class="form-group col-sm-12 panel panel-info">
          <div class="panel-heading head col-sm-12" style="background-color: #e8f4ff;margin-bottom: 10px">
            <div class="col-sm-6 text-left">设备{{$index+1}}信息</div>
            <div class="col-sm-6 text-right"><button
              class="button_delete button_spacing"
              v-if="!item.id && mark !== 1"
              @click.prevent="deleteDevicesinfo(i)"
            >删除</button></div>
            <div class="col-sm-6 text-right"><button
              class="button_delete button_spacing"
              v-if="item.id && mark !== 1 && item.f_operate_state === 1"
              @click.prevent="deleteDevices(item.id)"
            >删除</button></div>
            <div class="col-sm-6 text-right"><button
              class="button_delete button_spacing"
              v-if="item.id && mark !== 1 && item.f_operate_state === 0"
              @click.prevent="quChuDevices(item.id, '减少')"
            >减少</button></div>
            <div class="col-sm-6 text-right"><button
              class="button_delete button_spacing"
              v-if="item.id && mark !== 1 && item.f_operate_state === 2"
              @click.prevent="quChuDevices(item.id, '恢复')"
            >恢复</button></div>
            <div class="col-sm-6 text-right">
              <label class="col-sm-4 control-label" v-if="item.f_operate_state === 0">旧设备</label>
            </div>
            <div class="col-sm-6 text-right">
              <label class="col-sm-4 control-label" v-if="item.f_operate_state === 1">新设备</label>
            </div>
            <div class="col-sm-6 text-right">
              <label class="col-sm-4 control-label" v-if="item.f_operate_state === 2">标记减少设备</label>
            </div>
          </div>
          <div class="form-group col-sm-6" :class="[!item.f_devices_type ? 'has-error' : '']">
            <label class="col-sm-4 control-label">设备类型：</label>
            <div class="col-sm-8">
              <input-select
                class="select select_list"
                :value.sync="item.f_devices_type"
                v-model="item.f_devices_type"
                :options="devicesType"
                :disable="mark === 1 || item.f_operate_state === 0"
                :valueSingle="true"></input-select>
            </div>
          </div>
          <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">设备编号：</label>
            <div class="col-sm-8">
              <input class="form-control input_view" style=""
                     placeholder="设备编号"
                     v-model="item.f_devices_no"
                     :value="item.f_devices_no"
                     :readonly="mark === 1 || item.f_operate_state === 0"/>
            </div>
          </div>
          <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">设备品牌：</label>
            <div class="col-sm-8">
              <input class="form-control input_view" style=""
                     placeholder="设备品牌"
                     v-model="item.f_brand"
                     :value="item.f_brand"
                     :readonly="mark === 1 || item.f_operate_state === 0"/>
            </div>
          </div>
          <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">设备型号：</label>
            <div class="col-sm-8">
              <input class="form-control input_view" style=""
                     placeholder="设备型号"
                     v-model="item.f_devices_model"
                     :value="item.f_devices_model"
                     :readonly="mark === 1 || item.f_operate_state === 0"/>
            </div>
          </div>
          <div class="form-group col-sm-6" :class="[!item.f_devices_num ? 'has-error' : '']">
            <label class="col-sm-4 control-label">设备数量：</label>
            <div class="col-sm-8">
              <input class="form-control input_view" style="" type="number"
                     placeholder="设备数量"
                     v-model="item.f_devices_num"
                     :value="item.f_devices_num"
                     :readonly="mark === 1 || item.f_operate_state === 0"/>
            </div>
          </div>
          <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">设备功率：</label>
            <div class="col-sm-8">
              <input class="form-control input_view" style=""
                     placeholder="设备功率"
                     type="number"
                     v-model="item.f_devices_tonnage"
                     :value="item.f_devices_tonnage"
                     :readonly="mark === 1 || item.f_operate_state === 0"/>
            </div>
          </div>
          <div class="form-group col-sm-6">
            <label class="col-sm-4 control-label">安装日期：</label>
            <div class="col-sm-8">
              <input class="form-control input_view" style=""
                     placeholder="安装日期"
                     v-model="item.f_install_date"
                     :value="installdate(item.f_install_date)"
                     :readonly="mark === 1 || item.f_operate_state === 0"/>
            </div>
          </div>
          <div class="form-group col-sm-6" :class="[item.f_devices_tonnage && !item.f_devices_tonnage_unit ? 'has-error' : '']">
            <label class="col-sm-4 control-label">功率单位：</label>
            <div class="col-sm-8">
              <input class="form-control input_view" style=""
                     placeholder="功率单位"
                     v-model="item.f_devices_tonnage_unit"
                     :value="item.f_devices_tonnage_unit"
                     :readonly="mark === 1 || item.f_operate_state === 0"/>
            </div>
          </div>
        </div>

      </article>
      <footer slot="modal-footer" class="modal-footer">
        <template v-if="mark !== 1">
          <button type="button" class="btn btn-primary" @click="pushDevice()">添加设备</button>
          <button type="button" class="btn btn-primary" @click="addDevice(device)" :disabled="disabledBut">确认</button>
        </template>
      </footer>
    </modal>
  </div>
</template>
<script>
import {getNowDate,isEmpty} from '../../../Util'
import {PagedList} from 'vue-client'
import Vue from 'vue'
import {HttpResetClass} from 'vue-client'
// Date格式化
Date.prototype.Format = function (fmt) {
  var o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'H+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    'S': this.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  }
  return fmt
}

export default {
  title: '设备管理',
  props: {
    selectdata: {
      type: Object
    },
    mark: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      model: {
        data: null
      },
      devicesinfo: [],
      device: '',
      showDevices: false
    }
  },
  ready () {
    this.search()
  },
  methods: {
    async deleteUserinfo (row) {
      let res = await this.$showMessage('此操作不可撤回，您确定要删除这条记录吗？')
      if (res === 'cancel') {
        return
      }
      let data = {
        userinfo: row,
        selectdata: this.selectdata
      }
      res = await this.$resetpost('rs/logic/applyDeleteNewUserinfo', {data:data}, {
        resolveMsg: null,
        rejectMsg: '删除失败！！！'
      })

      this.$dispatch('breakControl', this.selectdata)
    },
    deleteDevices(index){
      this.$resetdelete(`rs/entity/t_middle_devices`, {id: index}, {resolveMsg: '删除成功', rejectMsg: '删除失败'}).then(async (res) => {
        //发送请求
        let data = {
          old_id: index
        }
        let res1 = await this.$resetpost(
          `rs/logic/applydeleteDevice`,
          {data: data},
          {resolveMsg: null, rejectMsg: '设备添加失败！！！'}
        )
        this.$dispatch('breakControl', this.selectdata)
      })
    },
    async quChuDevices(index, val) {
      let data = {
        id:index,
        state: val,
        selectdata: this.selectdata
      }
      await this.$resetpost('rs/logic/applyQuChuDevice', {data: data}, {
        resolveMsg: null,
        rejectMsg: '修改设备状态失败！！！'
      })
      this.$dispatch('breakControl', this.selectdata)
    },
    deleteDevicesinfo (index) {
      this.devicesinfo.splice(index, 1)
    },
    async addDevice (row) {
      if(this.devicesinfo.length > 0) {
        let data = {
          selectdata: this.selectdata,
          devicesinfo: this.devicesinfo,
          user: this.$login.f,
          f_userinfo_id: row ? row.f_userinfo_id : ''
        }
        let res = await this.$resetpost(
          `rs/logic/applyNewAddDevice`,
          {data: data},
          {resolveMsg: null, rejectMsg: '设备添加失败！！！'}
        )
      }
      this.$dispatch('breakControl', this.selectdata)
    },
    pushDevice () {
      this.devicesinfo.push({})
    },
    async openDevicesModal (row) {
      this.device = ''
      if (row) {
        this.device = row
        let data = {
          tablename: 't_middle_devices',
          condition: `f_userinfo_id = '${row.f_userinfo_id}' and f_modify_id = '${this.selectdata.f_modify_id}'`
        }
        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `rs/sql/applySingleTable`,
          {data: data},
          {resolveMsg: null, rejectMsg: '设备查询失败！！！'}
        )
        this.devicesinfo = res.data
      } else {
        this.pushDevice()
      }

      this.showDevices = true
    },
    async search () {
      let http = new HttpResetClass()
      let data = {
        condition: `ui.f_userinfo_id = '${this.selectdata.f_userinfo_id}'`,
        condition1: `f_modify_id = '${this.selectdata.f_modify_id}'`
      }
      let res = await http.load('POST', 'rs/sql/getChangeDevices', {data:data}, {
        resolveMsg: null,
        rejectMsg: '获取设备失败！！！'
      })
      this.model.data = res.data

      // 更改安装处数
      for (const item of this.selectdata.fields) {
        if (item.label === '安装处数') {
          item.value = this.model.data.length
          this.selectdata[item.field] = this.model.data.length
        }
      }
    },
    // 关闭对话框
    closeDevices() {
      this.showDevices = false
      this.devicesinfo = []

      this.search()
    }
  },
  events: {
  },
  computed: {
    showDeleteUserInfo () {
      return this.selectdata.f_apply_type === '非民用报建' &&
        (this.selectdata.defname === '报建受理' || this.selectdata.defname === '现场勘察')
    },
    disabledBut () {
      let disabledBut = true
      disabledBut = this.devicesinfo.every(item => {
        if (isEmpty(item.f_devices_tonnage)) {
          return !isEmpty(item.f_devices_type) && !isEmpty(item.f_devices_num)
        }
        return !isEmpty(item.f_devices_type) && !isEmpty(item.f_devices_num) && !isEmpty(item.f_devices_tonnage) && !isEmpty(item.f_devices_tonnage_unit)
      })
      return !disabledBut
    },
    // 安装人
    installperson () {
      return function (f_input_person) {
        if (isEmpty(f_input_person)) {
          return this.$login.f.name
        }
        return f_input_person
      }
    },
    installdate() {
      return function (f_install_date) {
        if (isEmpty(f_install_date)) {
          return new Date().Format('yyyy-MM-dd HH:mm:ss')
        }
        return f_install_date
      }
    },
    devicesType() {
      return this.$appdata.getParam("设备类型")
    }
  },
  watch: {
  }
}
</script>
<style scoped>
  .textNoLineBreak {
    white-space: nowrap;
  }
  .input_view{
    background-color: #ffffff;
    border-radius: 2px;
    border: solid 1px #c7c7c7!important;
    color: #333333!important;
    font-size: 15px!important;
  }

  .input_view[readonly]{
    border: 1px solid #DDD!important;
    color:#ACA899!important;
  }
  .input_view:disabled{
    border: 1px solid #DDD!important;
    color:#ACA899!important;
  }
</style>
