<template>
  <el-form
    :model="form"
    status-icon
    inline="true"
    :rules="rules"
    ref="form"
    label-width="100px"
    class="editor-device"
  >
    <h2 class="v-title" style="margin-bottom: 10px">基本信息设置</h2>
    <el-form-item style="width: 30%" :span="12" label="设备名称" prop="name">
      <el-input
        class="custom-input"
        maxlength="30"
        show-word-limit
        v-model="form.name"
        autocomplete="off"
      ></el-input>
    </el-form-item>
    <el-form-item label="设备键值" prop="keycode" style="width: 30%">
      <el-input
        class="custom-input"
        style="width: 80%"
        maxlength="30"
        show-word-limit
        v-model="form.keycode"
        autocomplete="off"
      ></el-input>
    </el-form-item>
    <el-form-item style="width: 30%" label="设备分类" prop="classify">
      <el-cascader
        :options="device_classify_list"
        v-model="form.classify"
        :props="{
          checkStrictly: true,
          value: 'id',
          label: 'name',
          children,
          emitPath: false,
        }"
      >
      </el-cascader>
    </el-form-item>
    <el-form-item label="设备分组" style="width: 30%" prop="groups">
      <el-input-number
        @change="changeNumber"
        v-model="form.groups"
        label="描述文字"
        :min="1"
        :max="100"
      ></el-input-number>
    </el-form-item>
    <el-form-item style="width: 40%" label="设备号位" prop="position">
      <el-select v-model="form.position" placeholder="请选择" value-key="id">
        <el-option
        v-for="v in postList"
        :key="v.id"
        :label="v.name"
        :value="v.id"
        />
      </el-select>
      <el-button
        @click="isShowPost = true"
        round
        style="margin-left: 10px"
        size="mini"
        type="primary"
        >维护号位</el-button
      >
    </el-form-item>

    <el-form-item label="设备IP" prop="groups" style="width: 100%">
      <DeviceIpTable :ips="form.ips" :groups="form.groups"></DeviceIpTable>
    </el-form-item>
    <el-form-item style="width: 100%" label="设备说明" prop="groups">
      <el-input
        maxlength="200"
        show-word-limit
        type="textarea"
        v-model="form.comment"
        label="描述文字"
      ></el-input>
    </el-form-item>
    <h2 class="v-title" style="margin-bottom: 10px">部件信息设置</h2>
    <div class="device-part-manage">
      <el-button
        size="mini"
        round
        type="primary"
        icon="el-icon-plus"
        @click="
          () => {
            currentPart = {};
            isShowCreateOperation = true;
          }
        "
        >新增部件</el-button
      >
      <el-button
      size="mini"
      round
      type="primary"
      @click="isShowOperation = true"
        >维护部件状态</el-button
      >
    </div>
    <DevicePartTable
      row-key="id"
      @editorOperation="
        (data) => {
          currentPart = JSON.parse(JSON.stringify(data));
          isShowCreateOperation = true;
        }
      "
      :part="form.part"
    ></DevicePartTable>
    <div class="from-footer">
      <el-button round type="danger" @click="cancel">取消</el-button>
      <el-button round type="primary" @click="onSubmit" :loading="isSaveLoading">{{
        this.form.id ? "保存" : "创建"
      }}</el-button>
    </div>
    <OperationManage v-model="isShowOperation"></OperationManage>
    <PostMnage v-model="isShowPost"></PostMnage>
    <CreatePart
      v-if="isShowCreateOperation"
      v-model="isShowCreateOperation"
      :partList="form.part"
      :currentPart="currentPart"
    ></CreatePart>
  </el-form>
</template>

<script>
// import DialogLayout from '@/components/layout/DialogLayout.vue'
import DeviceIpTable from './components/device-ip-table.vue'
import DevicePartTable from './components/device-part-table.vue'
import PostMnage from './components/post.vue'
import OperationManage from './components/operation.vue'
import CreatePart from './components/create-part.vue'
import { getPostApi } from '@/api/training/post'
import {
  getDeviceDetailsApi,
  getDeviceClassifyApi,
  createDevicesApi,
  editorDevicesApi
} from '@/api/training/device'
export default {
  props: {
    value: {
      type: Boolean,
      default: () => true
    }
  },
  data () {
    return {
      // 表格格式
      column: [],
      isShowPost: false,
      isShowOperation: false,
      isShowCreateOperation: false,
      form: { position: null, classify: null },
      baseForm: {
        name: '',
        keycode: '',
        position: null,
        groups: 1,
        comment: '',
        classify: null,
        part: [],
        ips: [
          {
            remarks: null,
            group: 1,
            ip: '127.0.0.1',
            comment: '示例IP'
          }
        ]
      },
      currentPart: {},
      routerQuery: null,
      rules: {
        name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        keycode: [{ required: true, message: '请输入设备键值', trigger: 'blur' }],
        classify: [
          {
            message: '请选择设备分类',
            trigger: 'change',
            required: true
            // validator: (r, v, c) => {
            //   console.log(this.form)
            //   return this.form.classify ? c() : c(new Error('请选择设备分类'))
            // }
          }
        ],
        position: [
          {
            message: '请选择设备号位',
            trigger: 'change',
            required: true
          }
        ]
      },
      postList: [],
      device_classify_list: [],
      isSaveLoading: false
    }
  },
  components: {
    // DialogLayout,
    DeviceIpTable,
    DevicePartTable,
    PostMnage,
    OperationManage,
    CreatePart
  },
  activated () {
    this.getInitData()
    this.$refs.form.clearValidate()
  },
  mounted () {},
  methods: {
    changeNumber (e) {
      const tableData = []
      for (let k = 0; k < e; k++) {
        tableData.push(
          { ...this.form.ips[k], group: k + 1 } || {
            group: k + 1,
            status: false
          }
        )
      }
      this.form.ips = tableData
    },
    cancel () {
      this.$router.push('/train/device')
    },
    // 提交编辑的信息
    async onSubmit () {
      this.isSaveLoading = true
      this.$refs.form.validate(async (isok) => {
        if (isok) {
          const errMessage = { ips: [] }
          this.form.ips.forEach((item) => {
            if (!this.checkIpFormat(item.ip)) {
              errMessage.ips.push(item.group + '组')
            }
          })
          this.checkPartsFormat()
          if (errMessage.ips.length > 0) {
            this.$message.error(
              `您的设备IP信息中，第【${errMessage.ips.join(
                '、'
              )}】 IP地址格式存在错误！请检查后再试！`
            )
            return
          }
          this.form.id
            ? await editorDevicesApi(this.form.id, this.form)
            : await createDevicesApi(this.form)
          this.$message.success('设备信息保存成功')
          this.cancel()
          this.isSaveLoading = false
        } else {
          this.isSaveLoading = false
        }
      })
    },
    checkPartsFormat () {
      const baseObj = {}
      console.log(this.form.part)
      this.form.part.forEach((item) => {
        baseObj[item.keycode] = item
      })
      this.form.part = Object.values(baseObj)
      console.log(Object.values(baseObj))
    },
    checkIpFormat (ip) {
      const ipPattern = /^(([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])$/
      return ipPattern.test(ip)
    },
    async findAllQuestionsClassify () {
      const { data } = await getDeviceClassifyApi()
      const list = [{ id: 'system', name: '设备分类', disabled: true, children: [] }]
      this.classify_default = data
      this.questionClassifyMap = {}
      this.questionClassifyMap = data.toTree()

      list[0].children = this.questionClassifyMap.tree
      this.device_classify_list = list
    },
    async getInitData () {
      this.routerQuery = this.$route.query
      const { data } = await getPostApi()
      this.postList = data
      if (this.routerQuery?.id) {
        const { data } = await getDeviceDetailsApi(this.routerQuery?.id)
        this.$set(this, 'form', JSON.parse(JSON.stringify(data)))
      } else {
        this.form = JSON.parse(JSON.stringify(this.baseForm))
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
      await this.findAllQuestionsClassify()
    }
  }
}
</script>

<style lang="scss" scoped>
.post-header {
  width: 100%;
  display: flex;
  justify-content: right;
  margin-bottom: 10px;
}
.editor-device {
  ::v-deep .el-form-item__content {
    width: calc(100% - 100px);
  }
}
.from-footer {
  width: 100%;
  display: flex;
  justify-content: center;
}
.device-part-manage {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>
