<template>
  <BaseDialog v-bind="$attrs" v-on="listeners" @submit="onSubmit" @closed="onClosed" :loading="loading" width="896px">
    <BaseTitle>监测站点基本信息</BaseTitle>
    <BasisForm ref="basis" v-model="formData.basis" :enable="enable" :labelWidth="labelWidth" />
    <BaseTitle>关联排水设施信息</BaseTitle>
    <ConnectForm ref="connect" v-model="formData.connect" :labelWidth="labelWidth" />
    <BaseTitle>设备安装信息</BaseTitle>
    <DeviceForm ref="device" v-model="formData.device" :types="types" :labelWidth="labelWidth" />
    <BaseTitle>设备监测指标</BaseTitle>
    <ThresholdForm
      ref="threshold"
      v-model="formData.threshold"
      :standards="standards"
      :labelWidth="labelWidth"
      :typeId="typeId"
      :levels="levels"
    />
  </BaseDialog>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import BaseDialog from '@/components/BaseDialog/index.vue'
import BaseTitle from '@/components/BaseTitle/index.vue'
import BasisForm from './BasisForm.vue'
import ConnectForm from './ConnectForm.vue'
import DeviceForm from './DeviceForm.vue'
import ThresholdForm from './ThresholdForm.vue'
import { IDeviceType, IPointDetail, IStandard, IPoint, IPointDetailResult } from '../../api/common'
import { standardPage } from '../../api/standard'
import { getDetail } from '../../api/point'
import { IDictionary } from '@/api/common'

interface IFormData {
  basis: {
    siteCode: string
    siteName: string
    sectionId: number
    siteAddress: string
    latitude: string
    longitude: string
    [x: string]: any
  }
  connect: {
    drainageId: number
    drainageName: string
    drainageRoadName: string
    drainageType: number
  }
  device: {
    typeId: number
    install: Partial<IPointDetailResult['installVo']>
  }
  threshold: {
    standardId: number
    items: Partial<IPointDetailResult['targetVos']>
  }
  fileList: IPointDetail['fileList']
}

const getDefaultFormData = () => ({
  basis: {
    /** 站点编号 */
    siteCode: undefined,
    /** 站点名称 */
    siteName: undefined,
    /** 断面Id */
    sectionId: undefined,
    /** 站点地址 */
    siteAddress: undefined,
    /** 纬度 */
    latitude: undefined,
    /** 经度 */
    longitude: undefined
  },

  connect: {
    /** 排水设施ID */
    drainageId: undefined,
    /** 排水设施名称 */
    drainageName: undefined,
    /** 排水设施所在道路名称 */
    drainageRoadName: undefined,
    /** 排水类型 */
    drainageType: undefined
  },

  // project: {
  //   /** 项目编码 */
  //   projectCode: undefined,
  //   /** 项目ID */
  //   projectId: undefined,
  //   /** 项目名称 */
  //   projectName: undefined
  // },

  device: {
    /** 设备类型ID */
    typeId: undefined,
    /** 设备安装信息 */
    install: {
      /** 设备ID */
      deviceId: undefined,
      /** 文件所属项目类型 */
      fileTypeID: 123,
      /** 安装人 */
      installPeople: undefined,
      /** 安装时间 */
      installTime: undefined,
      /** 联系人电话 */
      liaisonPhone: undefined,
      /** 关联状态0未启用,1启用（启用后不允许修改） */
      relevancyState: undefined,
      /** 站点ID */
      siteId: undefined
    },
    fileList: []
  },
  /** 指标阈值列表 */
  threshold: {
    standardId: undefined,
    items: []
  }
})
const getDefaultEnableValue = () => ({ coordinate: false, device: false })

@Component({
  name: 'PointForm',
  components: { BaseDialog, BaseTitle, BasisForm, ConnectForm, DeviceForm, ThresholdForm }
})
export default class PointForm extends Vue {
  @Prop({ type: Object, default: () => ({}) }) data!: object
  @Prop({ type: Boolean, default: false }) loading!: boolean
  @Prop({ type: Array, default: () => [] }) types!: IDeviceType[]
  @Prop({ type: Array, default: () => ({}) }) levels!: IDictionary[]

  $refs!: {
    basis: BasisForm
    connect: ConnectForm
    device: DeviceForm
    threshold: ThresholdForm
  }

  formData: Partial<IFormData> = getDefaultFormData()

  enable = getDefaultEnableValue()
  standards: IStandard[] = []
  labelWidth = '8em'

  get listeners() {
    const { submit, ...rest } = this.$listeners
    return rest
  }

  get typeId() {
    const { device: { typeId } = {} } = this.formData
    return typeId
  }

  async onSubmit() {
    const keys = ['basis', 'connect', 'device', 'threshold']
    const valid = !(await Promise.all(keys.map((key) => this.$refs[key].validate()))).some((item) => !item)
    if (valid) {
      console.log(this.formData)
      const { basis, connect, device, threshold } = this.formData
      const data: IPointDetail = {
        ...basis,
        ...connect,
        ...device,
        ...this.$store.getters['project/info'],
        targets: threshold.items as IPointDetail['targets']
      }
      this.$emit('submit', data)
    }
  }

  onClosed() {
    this.formData = getDefaultFormData()
    this.$emit('closed')
  }

  async getDetail(id: number) {
    const { result } = await getDetail(id)
    const { drainageId, drainageName, drainageRoadName, drainageType, targetVos, installVo, statuses, ...rest } =
      result || {}
    const typeId = ((targetVos || [])[0] || {}).typeId
    this.formData = {
      connect: { drainageId, drainageName, drainageRoadName, drainageType },
      device: { typeId, install: installVo || {} },
      threshold: {
        standardId: undefined,
        items: targetVos || []
      },
      basis: rest as IFormData['basis']
    }
  }

  @Watch('typeId')
  async getAllStandards(typeId) {
    try {
      const {
        result: { records }
      } = await standardPage({ typeId, current: 1, size: 9999 })
      this.standards = records || []
    } catch (error) {
      console.log(error)
    }
  }

  @Watch('data', { immediate: true })
  setDefaultData(val: IPoint) {
    if (val.id) {
      this.getDetail(val.id)
    } else {
      this.formData = getDefaultFormData()
    }
  }
}
</script>
