<template>
  <div class="app-container">
    <div class="level-title">
      <h1>{{ this.$parent.fireDeviceId === '' ? "新增" : "修改" }}</h1>
    </div>
    <div>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-row>
          <el-col :span="12">
            <el-row>
              <el-form-item label="消防区域：" prop="fireRegionId">
                <el-select v-model="form.fireRegionId" placeholder="请选择消防区域" class="filter-item" style="width: 100%;">
                  <el-option
                    v-for="item in varRegionList"
                    :key="item.fireRegionId"
                    :label="item.fireRegionName"
                    :value="item.fireRegionId"/>
                </el-select>
              </el-form-item>
            </el-row>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="消防点位：" prop="firePointId">
              <el-select v-model="form.firePointId" placeholder="请选择点位" style="width: 100%;">
                <el-option
                  v-for="item in pointList"
                  :key="item.firePointName"
                  :label="item.firePointName"
                  :value="item.firePointId"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责部门：" prop="departmentId">
              <el-select v-model="form.departmentId" placeholder="请选择负责部门" style="width: 100%;">
                <el-option
                  v-for="item in departmentList"
                  :key="item.DEPARTMENT_ID"
                  :label="item.DEPARTMENT_NAME"
                  :value="item.DEPARTMENT_ID"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="消防器材类型：" prop="fireDeviceTypeId">
              <el-select v-model="form.fireDeviceTypeId" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in typeData"
                  :key="item.NAME"
                  :label="item.NAME"
                  :value="item.BIANMA"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button v-show="form.fireDeviceTypeId" type="primary" style="margin-left: 16px;" @click="showDrawer">
              查看检查项
            </el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="消防器材编码：" prop="fireDeviceCode">
              <el-input v-model="form.fireDeviceCode" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="有效期开始/结束时间：" prop="validityTime">
              <el-date-picker
                v-model="validityTime"
                type="daterange"
                start-placeholder="有效期开始日期"
                end-placeholder="有效期结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="存放地点：" prop="remake">
              <el-input
                :autosize="{ minRows: 3, maxRows: 5}"
                v-model="form.remake"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="ui-foot">
      <el-button type="success" @click="confirm">保 存</el-button>
      <el-button plain type="info" @click="goBack">返 回</el-button>
    </div>
    <el-drawer
      :visible.sync="drawer"
      direction="rtl"
      title="检查项列表">
      <el-table :data="checkStandardList" border>
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column property="FIRE_CHECK_STANDARD_ITEM" label="检查项"/>
      </el-table>
    </el-drawer>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { requestFN } from '@/utils/request'
import SelectTree from '@/components/SelectTree'
import waves from '@/directive/waves'
import dateformat from '../../../../utils/dateformat'

export default {
  components: { Pagination, SelectTree },
  directives: { waves },
  data() {
    return {
      drawer: false,
      checkStandardList: [],
      validityTime: [],
      departmentList: [],
      form: {
        fireDeviceId: '',
        firePointId: '',
        fireRegionId: '',
        departmentId: '',
        fireDeviceCode: '',
        fireDeviceTypeId: '',
        remake: ''
      },
      rules: {
        fireDeviceTypeId: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
        fireDeviceCode: [{ required: true, message: '请输入设备编码', trigger: 'blur' }],
        firePointId: [{ required: true, message: '请选择消防点位', trigger: 'change' }],
        fireRegionId: [{ required: true, message: '请选择消防区域', trigger: 'change' }],
        departmentId: [{ required: true, message: '请选择负责部门', trigger: 'change' }],
        remake: [{ required: true, message: '请输入存放地点', trigger: 'blur' }]
      },
      pointList: [],
      varRegionList: [],
      treeData: [],
      typeData: [],
      deForm: {
        DEPARTMENT_ID: '',
        DEPARTMENT_NAME: ''
      }
    }
  },
  /**
   * 监听区域id
   *
   * @param newVal 新值
   * @param oldVal 旧值
   */
  watch: {
    'form.fireRegionId': {
      handler(newVal, oldVal) {
        if (oldVal) this.form.firePointId = ''
        this.$nextTick(() => {
          this.getPointByRegionId(newVal)
          this.getPointDepartmentId(newVal)
        })
      },
      immediate: false
    }
  },
  /**
   * @description 初始化数据
   *
   * @returns {Promise<void>}
   */
  async created() {
    this.getFireRegion()
    this.getTreeData()
    if (this.$parent.fireDeviceId != null && this.$parent.fireDeviceId !== '') {
      this.getDeviceInfo(this.$parent.fireDeviceId)
    }
    this.getDict()
  },
  methods: {
    /**
     * 获取检查项列表
     */
    showDrawer() {
      this.getStandardListByDeviceType(this.form.fireDeviceTypeId)
      this.drawer = true
    },
    /**
     * 根据设备类型获取检查项列表
     *
     * @param fireDeviceTypeId 设备类型
     */
    getStandardListByDeviceType(fireDeviceTypeId) {
      requestFN(
        '/fireCheckStandard/getStandardListByDeviceType',
        {
          FIRE_DEVICE_TYPE: fireDeviceTypeId
        }
      ).then((data) => {
        this.checkStandardList = data.varList
      })
    },
    /**
     * 根据区域获取负责的部门
     *
     * @param fireRegionId 区域ID
     */
    getPointDepartmentId(fireRegionId) {
      this.listLoading = true
      this.deForm.DEPARTMENT_ID = ''
      this.deForm.DEPARTMENT_NAME = ''
      requestFN(
        '/fire/region/v2/info',
        {
          fireRegionId: fireRegionId
        }
      ).then((data) => {
        this.listLoading = false
        this.deForm.DEPARTMENT_ID = data.res.departmentId
        this.form.departmentId = data.res.departmentId
        this.deForm.DEPARTMENT_NAME = data.res.departmentName
        this.departmentList = []
        this.departmentList.push(this.deForm)
      }).catch(() => {
        this.listLoading = false
      })
    },
    /**
     * 获取设备类型列表
     */
    getDict() {
      requestFN(
        'dictionaries/getLevels',
        {
          DICTIONARIES_ID: '249151f04fd64132a949fdd430a7b9c5'
        }
      ).then((data) => {
        this.typeData = data.list
      })
        .catch(() => {
          this.listLoading = false
        })
    },
    /**
     * 根据区域id获取点位列表
     */
    getPointByRegionId(fireRegionId) {
      requestFN(
        '/fire/point/v2/list',
        { fireRegionId: fireRegionId }
      ).then((data) => {
        this.$nextTick(() => {
          this.pointList = data.varList
          if (data.varList != null && data.varList.length === 1) {
            this.form.firePointId = data.varList[0].firePointId
          }
        })
      })
    },
    /**
     * 获取部门列表
     */
    getTreeData() {
      requestFN(
        '/department/listTree',
        {}
      ).then((data) => {
        this.treeData = JSON.parse(data.zTreeNodes)
      })
    },
    /**
     * 获取区域列表
     */
    getFireRegion() {
      requestFN(
        '/fire/region/v2/list',
        {}
      ).then((data) => {
        this.varRegionList = data.varList
      })
    },
    /**
     * 提交
     */
    confirm() {
      this.listLoading = true
      // 校验器材code是否重复
      requestFN(
        '/fire/device/v2/code',
        {
          fireDeviceCode: this.form.fireDeviceCode,
          id: this.form.fireDeviceId
        }
      ).then((data) => {
        if (data.result !== 'success') {
          this.$message.warning('消防器材编码重复')
          return
        }
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.$parent.fireDeviceId === '') {
              this.handleAdd()
            } else {
              this.handleUpdate()
            }
          }
        })
      }).catch(() => {
        this.listLoading = true
      })
    },
    /**
     * 新增器材
     */
    handleAdd() {
      this.listLoading = true
      this.form.validityStartTime = dateformat(this.validityTime[0], 'YYYY-MM-DD')
      this.form.validityEndTime = dateformat(this.validityTime[1], 'YYYY-MM-DD')
      requestFN(
        '/fire/device/v2/save',
        this.form
      ).then(() => {
        this.$parent.activeName = 'List'
        this.$parent.$refs.list.getList()
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    /**
     * 修改器材
     */
    handleUpdate() {
      if (!this.validityTime) {
        this.validityTime = []
      }
      requestFN(
        '/fire/device/v2/update',
        {
          fireDeviceId: this.form.fireDeviceId,
          firePointId: this.form.firePointId,
          fireRegionId: this.form.fireRegionId,
          departmentId: this.form.departmentId,
          fireDeviceCode: this.form.fireDeviceCode,
          fireDeviceTypeId: this.form.fireDeviceTypeId,
          validityStartTime: dateformat(this.validityTime[0], 'YYYY-MM-DD'),
          validityEndTime: dateformat(this.validityTime[1], 'YYYY-MM-DD'),
          remake: this.form.remake
        }
      ).then(() => {
        this.listLoading = false
        this.dialogFormEdit = false
        this.$parent.activeName = 'List'
        this.$parent.$refs.list.getList()
      }).catch(() => {
        this.listLoading = false
      })
    },
    /**
     * 获取器材详情
     */
    getDeviceInfo(deviceId) {
      requestFN(
        '/fire/device/v2/info',
        { id: deviceId }
      ).then((data) => {
        this.form.fireDeviceId = data.res.fireDeviceId
        this.form.firePointId = data.res.firePointId
        this.form.fireRegionId = data.res.fireRegionId
        this.form.fireDeviceCode = data.res.fireDeviceCode
        this.form.fireDeviceTypeId = data.res.fireDeviceTypeId
        this.$set(this.validityTime, 0, dateformat(data.res.validityStartTime, 'YYYY-MM-DD'))
        this.$set(this.validityTime, 1, dateformat(data.res.validityEndTime, 'YYYY-MM-DD'))
        this.form.departmentId = data.res.departmentId
        this.form.remake = data.res.remake
      })
    },
    /**
     * 返回列表
     */
    goBack() {
      this.$parent.activeName = 'List'
    }
  }
}
</script>
