<template>
  <div class="auto">
    <modal :show.sync="show_devices" width="80%" title="表具设备信息" v-ref:modal large backdrop="false">
      <header slot="modal-header" class="modal-header">
        <span class="glyphicon glyphicon-remove closebtn" @click="closeModal"></span>
      </header>
      <article slot="modal-body" class="modal-body" style="height: auto" v-show="!showTable">
        <div class="flex-row flex-deviceinfo">
          <div class="flex-row flex-two-info panel panel-default" v-for="(index,row) in devicesinfo">
            <avatar-upload :img-src.sync="row.img.content" :filename.sync="row.img.filename"></avatar-upload>
            <form class="form-horizontal select-overspread " style="flex: 1;">
              <div style="margin-top: 2%">
                <img style="margin-top: -2px;margin-left: 2px" src="../../../../static/images/lefticon/矩形1183.png">
                <a style="font-size: 16px;font-weight: 500;">设备基本信息</a>&nbsp;<a
                style="color: #999999;text-decoration: none"></a>
              </div>
              <div class="row auto" style="margin-top: 10px;margin-left: 10px;">
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">设备类型</label>
                  <v-select :value.sync="row.f_devices_type" v-model="row.f_devices_type"
                            :options='devicetypes' placeholder='设备类型' :value-single="true"
                            close-on-select></v-select>
                </div>
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class=" font_normal_body">设备编号</label>
                  <input type="text" class="input_search" style="width:60%" v-model="row.f_devices_no"
                         @blur="devicesNoBlur(index)"
                         placeholder='设备编号' v-next-el="{id: $index+'brand'}">
                </div>
              </div>
              <div class="row auto" style="margin-left: 10px;" v-if="row.f_devices_type != '报警器'">
                <div class="col-sm-6 form-group" style="padding-right: 5px;"
                     :class="[!row.f_brand && (row.f_devices_type == '壁挂炉' || row.f_devices_type == '热水器') ? 'has-error' : '']">
                  <label class="font_normal_body">设备品牌</label>
                  <input type="text" class="input_search" style="width:60%" v-model="row.f_brand" placeholder='设备品牌'
                         v-next-el="{id: $index+'devicesmodel'}" :id="$index+'brand'">
                </div>
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">设备型号</label>
                  <input type="text" class="input_search" style="width:60%" v-model="row.f_devices_model"
                         placeholder='设备型号' :id="$index+'devicesmodel'">
                </div>
              </div>
              <div class="row auto" style="margin-left: 10px;" v-if="row.f_devices_type == '报警器'">
                <div class="col-sm-6 form-group" style="padding-right: 5px;"
                     :class="[!row.f_brand && (row.f_devices_type == '壁挂炉' || row.f_devices_type == '热水器') ? 'has-error' : '']">
                  <label class="font_normal_body">设备品牌</label>
                  <v-select :value.sync="row.f_brand" v-model="row.f_brand"
                            :options='brands' placeholder='设备品牌' :value-single="true"
                            :onchange="brandChange(index)"
                            close-on-select>
                  </v-select>
                </div>
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">设备型号</label>
                  <v-select :value.sync="row.f_devices_model" v-model="row.f_devices_model"
                            :options='devicesModel' placeholder='设备型号' :value-single="true"
                            :onchange="modelChange(index)"
                            close-on-select>
                  </v-select>
                </div>
              </div>
              <div class="row auto" style="margin-left: 10px;">
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">施工单位</label>
                  <v-select :value.sync="row.f_builderunit" v-model="row.f_builderunit"
                            :options='builders' placeholder='施工单位' :value-single="true"
                            close-on-select></v-select>
                  <!--<input type="text" class="input_search" style="width:60%" v-model="row.f_builderunit"-->
                  <!--placeholder='施工单位'>-->
                </div>
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">联系电话</label>
                  <input type="text" class="input_search" style="width:60%" v-model="row.f_builder_phone"
                         placeholder='施工单位联系方式'>
                </div>
              </div>
              <div class="row auto" style="margin-left: 10px;" v-if="row.f_devices_type == '报警器'">
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">imei码&emsp;</label>
                  <input type="text" class="input_search" style="width:60%" v-model="row.f_imei"
                         placeholder='imei码'>
                  <!--<input type="text" class="input_search" style="width:60%" v-model="row.f_builderunit"-->
                  <!--placeholder='施工单位'>-->
                </div>
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">imsi码&emsp;</label>
                  <input type="text" class="input_search" style="width:60%" v-model="row.f_imsi"
                         placeholder='imsi码'>
                </div>
              </div>
              <div class="row auto" style="margin-left: 10px;">
                <div class="col-sm-6 form-group" style="padding-right: 5px;"
                     :class="[row.f_devices_type == '壁挂炉' && (row.f_input_person == '' || row.f_input_person == null) ? 'has-error' : '']">
                  <label class="font_normal_body">安装人&nbsp;&nbsp;&nbsp;</label>
                  <!--                  <input type="text" class="input_search" style="width:60%" v-model="row.f_input_person"-->
                  <!--                         placeholder='安装人'>-->
                  <v-select :value.sync="row.f_input_person" v-model="row.f_input_person"
                            :options='installperson' placeholder='安装人'
                            close-on-select></v-select>
                </div>
                <div class="col-sm-6 form-group" style="padding-right: 5px;"
                     :class="[row.f_devices_type == '壁挂炉' && row.f_input_date == '' ? 'has-error' : '']">
                  <label class="font_normal_body">安装日期</label>
                  <datepicker placeholder="安装日期" style="width: 60%"
                              v-model="row.f_input_date"
                              :value.sync="row.f_input_date"
                              :format="'yyyy-MM-dd'">
                  </datepicker>
                </div>
              </div>
              <div class="row auto" style="margin-left: 10px;">
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">生产日期</label>
                  <datepicker placeholder="生产日期" style="width: 60%"
                              v-model="row.f_make_date"
                              :value.sync="row.f_make_date"
                              :onchange="expireDate($index)"
                              :format="'yyyy-MM-dd'">
                  </datepicker>
                </div>
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">使用年限</label>
                  <input type="number" class="input_search" style="width: 60%" v-model="row.f_service_life"
                         :value.sync="row.f_service_life"
                         :onchange="expireDate($index)">
                </div>
              </div>
              <div class="row auto" style="margin-left: 10px;">
                <div class="col-sm-6 form-group" style="padding-right: 5px;" v-if="devicesinfoShow">
                  <label class="font_normal_body">到期日期</label>
                  <input type="test" class="input_search" style="width: 60%" v-model="row.f_expire_date"
                         :value.sync="row.f_expire_date"
                         placeholder="到期日期" disabled></input>
                </div>
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">设备数量</label>
                  <input type="text" class="input_search" style="width:60%" v-model="row.f_devices_num"
                         :value.sync="row.f_devices_num"
                         placeholder='设备数量' :id="$index+'devicesmodel'">
                </div>
              </div>
              <div class="row auto" style="margin-left: 10px;">
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body" title="用户设备状态">设备状态</label>
                  <v-select :value.sync="row.f_userinfodevices_state" v-model="row.f_userinfodevices_state"
                            :options='userdevicestate' placeholder='设备状态' :value-single="true"

                            close-on-select></v-select>
                </div>
                <div class="col-sm-6 form-group" style="padding-right: 5px;"
                     :class="[row.f_devices_type == '壁挂炉' && row.watchpurchase == '' ? 'has-error' : '']">
                  <label class="font_normal_body">购买方式</label>
                  <v-select :value.sync="row.watchpurchase" v-model="row.watchpurchase"
                            :options='WatchPurchases' placeholder='购买方式' :value-single="true"
                            close-on-select></v-select>
                </div>
              </div>
              <div class="row auto" style="margin-left: 10px;">
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">安装方式</label>
                  <v-select :value.sync="row.f_install_type" v-model="row.f_install_type"
                            :options='installtype' placeholder='安装方式' :value-single="true"
                            close-on-select></v-select>
                </div>
                <div style="" class="col-sm-6 form-group">
                  <label for="f_comments" class="font_normal_body ">&nbsp;&nbsp;&nbsp;备&nbsp;&nbsp;&nbsp;注</label>
                  <input class="input_search" style="width:60%" v-model="row.f_comments"/>
                </div>
              </div>
              <div>
                <img style="margin-top: -2px;margin-left: 2px" src="../../../../static/images/lefticon/矩形1183.png">
                <a style="font-size: 16px;font-weight: 500;">连接管信息</a>&nbsp;<a
                style="color: #999999;text-decoration: none"></a>
              </div>
              <div class="row auto" style="margin-left: 10px;">
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">管道类型</label>
                  <v-select :value.sync="row.f_pipe_type" v-model="row.f_pipe_type"
                            :options='pipetypes' placeholder='管道类型' :value-single="true"
                            close-on-select></v-select>
                </div>
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body" title="连接管安装日期">安装日期</label>
                  <datepicker placeholder="连接管安装日期" style="width: 60%"
                              v-model="row.f_pipeinstall_date"
                              :value.sync="row.f_pipeinstall_date"
                              :onchange="ljgexpireDate($index)"
                              :format="'yyyy-MM-dd'">
                  </datepicker>
                </div>
              </div>
              <div class="row auto" style="margin-left: 10px;">
                <div class="col-sm-6 form-group" style="padding-right: 5px;">
                  <label class="font_normal_body">使用年限</label>
                  <input type="number" class="input_search" style="width: 60%" v-model="row.f_service_liferg"
                         :value.sync="row.f_service_liferg"
                         :onchange="ljgexpireDate($index)">
                </div>
                <div class="col-sm-6 form-group" style="padding-right: 5px;" v-if="ljgDevicesinfoShow">
                  <label class="font_normal_body" title="连接管到期日期">到期日期</label>
                  <datepicker placeholder="连接管到期日期" style="width: 60%"
                              v-model="row.f_pipeexpire_date"
                              :value.sync="row.f_pipeexpire_date"
                              :format="'yyyy-MM-dd'">
                  </datepicker>
                </div>
              </div>
            </form>
            <img :src="imgdelete" alt="图片加载失败" class="img-rounded"
                 style="width: 60px;padding: 20px;margin-left: -15px;cursor: pointer;"
                 @click="deleteDevice($index, row)">
          </div>
          <div class="panel panel-default flex-two-info text-center" style="line-height: 164px;">
            <img :src="imgadd" alt="图片加载失败1" class="img-rounded"
                 style="width: 60px;padding: 10px;cursor: pointer;"
                 @click="addDevice()">
          </div>
        </div>
        <div class="row">
          <div class="text-right">
            <button @click="showTableBtn()" class="button_search button_spacing">列表显示
            </button>
          </div>
        </div>
      </article>
      <article slot="modal-body" class="modal-body" style="height: auto" v-show="showTable">
        <div class="row">
          <div class=" text-center">
            <table class="table table-striped table-bordered">
              <tr align="center">
                <th style="text-align: center">序号</th>
                <th style="text-align: center">设备类型</th>
                <th style="text-align: center">设备编号</th>
                <th style="text-align: center">设备品牌</th>
                <th style="text-align: center">设备型号</th>
                <th style="text-align: center">管道类型</th>
                <th style="text-align: center">安装人</th>
                <th style="text-align: center">安装方式</th>
                <th style="text-align: center">安装日期</th>
                <th style="text-align: center">生产日期</th>
                <th style="text-align: center">设备状态</th>
                <th style="text-align: center">备注</th>
                <th style="text-align: center">操作</th>
              </tr>
              <tr style="text-align: center" v-for="row in devicesinfo">
                <td style="text-align: center;">{{ $index + 1 }}</td>

                <td style="text-align: center">{{ row.f_devices_type }}</td>
                <td style="text-align:center">{{ row.f_devices_no }}</td>
                <td style="text-align: center">{{ row.f_brand }}</td>
                <td style="text-align: center">{{ row.f_devices_model }}</td>
                <td style="text-align: center">{{ row.f_pipe_type }}</td>
                <td style="text-align:center">{{ row.f_input_person }}</td>
                <td style="text-align:center">{{ row.f_install_type }}</td>
                <td style="text-align:center">{{ row.f_input_date }}</td>
                <td style="text-align:center">{{ row.f_make_date }}</td>
                <td style="text-align:center">{{ row.f_userinfodevices_state }}</td>
                <td style="text-align:center">{{ row.f_comments }}</td>
                <td style="text-align: center">
                  <img :src="imgdelete" alt="图片加载失败" class="img-rounded"
                       style="width: 60px;padding: 20px;margin-left: -15px;cursor: pointer;"
                       @click="deleteDevice($index, row)">
                </td>
              </tr>
            </table>
          </div>
        </div>
        <div class="row">
          <div class="text-right">
            <button @click="showTableBtn()" class="button_search button_spacing">添加表具设备
            </button>
          </div>
        </div>
      </article>

      <footer slot="modal-footer" class="modal-footer">
      </footer>
    </modal>
  </div>

</template>

<script>
import moment from 'moment'
import {HttpResetClass} from 'vue-client'

export default {
  title: '表具设备信息',
  data() {
    return {
      showTable: false,
      imgdelete: '/images/mainicon/deletedevice.png',
      imgadd: '/images/mainicon/adddevice.png',
      devicetypes: this.$appdata.getParam('设备类型'),
      pipetypes: this.$appdata.getParam('管道类型'),
      WatchPurchases: this.$appdata.getParam('购买方式'),
      installperson: this.$appdata.getParam('安装人'),
      installtype: this.$appdata.getParam('安装方式'),
      userdevicestate: this.$appdata.getParam('用户设备状态'),
      builders: this.$appdata.getParam('施工单位'),
      brands: [],
      devicesModel: [],
      f_make_date: '',
      f_expire_date: '',
      f_service_life: 0,
      devicesinfoShow: true,
      ljgDevicesinfoShow: true
    }
  },
  props: {
    devicesinfo: {
      type: Array
    },
    show_devices: {
      type: Boolean,
      default: false
    },
    f_input_person: {
      type: String,
      default: undefined
    }
  },
  computed: {
    // installperson () {
    //   // return this.$login.f.f_installman
    //   let rs = new Array()
    //   for (let i = 0; i < this.$login.f.f_installman.length; i++) {
    //     let temp = {
    //       label: this.$login.f.f_installman[i].name,
    //       value: this.$login.f.f_installman[i].name
    //     }
    //     rs.push(temp)
    //   }
    //   return rs
    // },
  },
  ready () {
    this.initParams()
  },
  methods: {
    async devicesNoBlur (index) {
      if (!this.devicesinfo[index].id) {
        if (this.devicesinfo[index].f_devices_type == '报警器') {
          console.log('看看进来了吗？')
          let http = new HttpResetClass()
          let data = {
            items: 'id',
            tablename: 't_devices',
            condition: `f_devices_type = '报警器' and f_devices_no = '${this.devicesinfo[index].f_devices_no}'`,
            orderitem: 'id'
          }
          let res = await http.load('post', 'rs/sql/saleSingleTable', {data: data}, {resolveMsg: null, rejectMsg: null})
          if (res.data.length > 0) {
            this.$showAlert(`报警器编号必须唯一，请重新输入报警器编号`, 'warning', 3000)
            this.devicesinfo[index].f_devices_no = ''
          }
        }
      }
    },
    async initParams () {
      try {
        let http = new HttpResetClass()
        let data = {
          items: 'id,f_brand',
          tablename: 't_iot_device_brand',
          condition: `1=1`,
          orderitem: 'id'
        }
        let res = await http.load('post', 'rs/sql/saleSingleTable', {data: data}, {resolveMsg: null, rejectMsg: null})
        this.brands = []
        for (let row of res.data) {
          this.brands.push({label: row.f_brand, value: row.f_brand, data: row})
        }
      } catch (e) {
        console.log(e)
      }
    },
    findbyid (list, name) {
      var result
      list.forEach((row, n) => {
        if (name == row.value) {
          result = row.data
        }
      })
      return result
    },
    showTableBtn () {
      this.showTable = !this.showTable
      console.log('表具信息', this.devicesinfo)
    },
    expireDate (index) {
      if (this.devicesinfo[index].f_make_date === '' || this.devicesinfo[index].f_make_date === undefined || this.devicesinfo[index].f_service_life === 0 || this.devicesinfo[index].f_service_life === undefined) {

      } else {
        var b = new Date(this.devicesinfo[index].f_make_date)
        var year = (b.getFullYear() - 0) + (this.devicesinfo[index].f_service_life - 0)
        var month = (b.getMonth() - 0) + 1
        var day = b.getDate()
        // this.$set(this.devicesinfo, index, {f_expire_date: year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day)})
        this.devicesinfo[index].f_expire_date = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day)
        this.devicesinfoShow = false
        this.$nextTick(() => {
          this.devicesinfoShow = true
        })
      }
    },
    ljgexpireDate (index) {
      if (this.devicesinfo[index].f_pipeinstall_date === '' || this.devicesinfo[index].f_pipeinstall_date === undefined || this.devicesinfo[index].f_service_liferg === 0 || this.devicesinfo[index].f_service_liferg === undefined) {

      } else {
        var b = new Date(this.devicesinfo[index].f_pipeinstall_date)
        var year = (b.getFullYear() - 0) + (this.devicesinfo[index].f_service_liferg - 0)
        var month = (b.getMonth() - 0) + 1
        var day = b.getDate()
        // this.$set(this.devicesinfo, index, {f_expire_date: year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day)})
        this.devicesinfo[index].f_pipeexpire_date = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day)
        this.ljgDevicesinfoShow = false
        this.$nextTick(() => {
          this.ljgDevicesinfoShow = true
        })
      }
    },
    async brandChange (index) {
      console.log('this.devicesinfo[index].f_brand', this.devicesinfo[index].f_brand)
      this.devicesModel = []
      if (this.devicesinfo.length > 0) {
        if (this.devicesinfo[index].f_devices_type == '报警器') {
          if (this.devicesinfo[index].f_brand) {
            this.devicesinfo[index].f_brand_id = this.findbyid(this.brands, this.devicesinfo[index].f_brand).id
            let http = new HttpResetClass()
            let data = {
              items: 'id,f_model',
              tablename: 't_iot_device_model',
              condition: `f_brand_id = ${this.devicesinfo[index].f_brand_id}`,
              orderitem: 'id'
            }
            let res = await http.load('post', 'rs/sql/saleSingleTable', {data: data}, {
              resolveMsg: null,
              rejectMsg: '获取设备型号失败!'
            })
            for (let row of res.data) {
              this.devicesModel.push({label: row.f_model, value: row.f_model, data: row})
            }
          }
        }
      }
    },
    async modelChange (index) {
      console.log('this.devicesinfo[index].f_devices_model', this.devicesinfo[index].f_devices_model)
      if (this.devicesinfo.length > 0) {
        if (this.devicesinfo[index].f_devices_type == '报警器') {
          if (this.devicesinfo[index].f_devices_model) {
            this.devicesinfo[index].f_devices_model_id = this.findbyid(this.devicesModel, this.devicesinfo[index].f_devices_model).id
          }
        }
      }
    },
    deleteDevice (index, row) {
      console.log('删除的信息', row)
      if (row.id) {
        this.$showMessage('此操作无法还原，是否确定要删除此设备？', ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            this.$resetpost('rs/logic/deletedevices', {param: row}, {
              resolveMsg: `成功删除此设备`,
              rejectMsg: '删除设备失败'
            }).then((res) => {
              this.devicesinfo.splice(index, 1)
            })
          }
        })
      } else {
        this.devicesinfo.splice(index, 1)
      }
    },
    addDevice () {
      console.log('设备信息', this.devicesinfo)
      this.devicesinfo.push({
        f_devices_type: '家用灶具',
        f_input_person: this.f_input_person,
        f_userinfodevices_state: '正常',
        f_input_date: this.$login.toStandardTimeString()
      })
    },
    closeModal () {
      let cannotclose = false
      let deleteData = []
      for (let [index, row] of this.devicesinfo.entries()) {
        switch (row.f_devices_type) {
          case '壁挂炉':
            if (!(row.f_brand && row.f_input_person && row.f_input_date && row.watchpurchase)) {
              deleteData.push(index)
              cannotclose = true
            }
            break
          case '热水器':
            if (!(row.f_brand)) {
              deleteData.push(index)
              cannotclose = true
            }
            break
        }
      }
      if (cannotclose) {
        this.$showMessage('新增设备有必填项没有填写，如果此时退出当前页面数据会丢失，请确定是否退出？', ['confirm', 'cancel']).then(async (res) => {
          if (res === 'confirm') {
            for (let i = deleteData.length - 1; i >= 0; i--) {
              this.devicesinfo.splice(deleteData[i], 1)
            }
            this.show_devices = false
          }
        })
      } else {
        this.show_devices = false
      }
    }
  }
}
</script>
<style lang="less">
.flex-deviceinfo {
  padding: 0px 20px;
  justify-content: space-between;
  height: auto;
  flex-wrap: wrap;
}

.flex-two-info {
  margin-bottom: 10px;
  align-items: center;
  width: 48%;
}
</style>
