<template>
    <div>
        <!-- <bread></bread> -->
        <div class="margin-view"></div>
        <div class="btn-view">
            <el-button class="btn" @click="btnClick">{{ id? '保存修改': '新建'}}</el-button>
        </div>
        <div class="content-view">
            <el-form label-width="10px" style="width:400px;" :model="formData" class="dcenter">
                <el-form-item label="">
                    <el-input v-model="formData.Name" placeholder="请输入数据源名称"></el-input>
                </el-form-item>
            </el-form>
            <el-input type="textarea" class="edit-textarea dcenter block" v-model="formData.Description" placeholder="请维护数据源说明"></el-input>
            <el-form label-width="120px" style="width:400px;" :model="formData" class="dcenter">
                <el-form-item label="协议类型">
                    <el-select v-model="formData.ProtocolType" filterable @change="handleChangeProtocolType" placeholder="请选择">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="主机IP地址" v-if="formData.ProtocolType != 'common'">
                    <ip-input :ip="formData.ProtocolInfo.Ip" :port="formData.ProtocolInfo.Port" :ProtocolType="formData.ProtocolType" @change="changeItem" @deletePort="deletePort"></ip-input>
                </el-form-item>
                <el-form-item label="用户名/密码" v-if="(passWordArr.indexOf(formData.ProtocolType) > -1)">
                    <el-input v-model="formData.ProtocolInfo.User" style="display:inline-block;width:100px;"></el-input>/
                    <el-input v-model="formData.ProtocolInfo.Password" style="display:inline-block;width:100px;"></el-input>
                </el-form-item>
                <el-form-item label="ProgId" v-if="formData.ProtocolType == 'opc'">
                    <el-input v-model="formData.ProtocolInfo.ProgId" style="display:inline-block;width:100px;"></el-input>
                </el-form-item>
                <el-form-item label="属性详情" v-if="formData.ProtocolType == 'common'">
                    <el-input type="textarea" :autosize="{ minRows: 8, maxRows: 8}" v-model="ProtocolInfo"  placeholder="请输入json格式数据" style="display:inline-block;width:400px;"> </el-input>
                </el-form-item>
                <el-form-item label="采集间隔时间">
                    <el-input-number v-model="formData.CollectInterval" controls-position="right" @change="handleChange" :min="10"></el-input-number>&nbsp;&nbsp;s
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
<script>
  import ipInput from "@/components/config_point/ip_input"
  // import bread from "components/common/bread_crumb"
  import tools from "@/utils/tools"
  import {createDataSource, queryDataSource, updateDataSource} from "@/fetch/point_http"
  import {mapGetters} from "vuex";

  export default {
    computed: {
      ...mapGetters("layout", [
        "projectId"
      ])
    },
    data() {
      return {
        passWordArr: ['mqtt', 'amqp', 'opc'],
        formData: {
          ProtocolType: "", //协议类型
          ProtocolStandarded: true,
          Name: "",
          ProtocolInfo: {
            Ip: "", //ip
            Port: "", //端口号，有些协议类型没有该信息
            User: "", //用户名
            Password: "", //密码
            ProgId: "", //progId
          },
          Description: "",
          CollectInterval: 10
        },
        ProtocolInfo: "",//自定义协议信息
        options: [{
          value: 'modbus-tcp',
          label: 'Modbus TCP'
        }, {
          value: 'bacnet-ip',
          label: 'BACNet IP'
        }, {
          value: 'opc',
          label: 'OPC'
        }, {
          value: 'knx',
          label: 'KNX'
        }, {
          value: 'mqtt',
          label: 'MQTT'
        }, {
          value: 'amqp',
          label: 'AMQP'
        }, {
          value: 'lora',
          label: 'LoRa'
        }, {
          value: 'ems-collect',
          label: 'ems-collect'
        }, {
          value: 'common',
          label: '其他'
        }],
        id: this.$route.query.key
      }
    },
    components: {
      ipInput,
      // bread
    },
    created() {
      this.$store.dispatch('setBreadcrumb', [{
        label: '系统集成',
                path: '/point/pointsetting'
            }, {
                label: '子系统点位接入',
                path: '/point/pointsetting'
            }, {
                label: this.id ? '编辑数据源' : '添加数据源'
            }])
        },
        mounted() {
            if (!!this.id) {
                this.getDataSouse()
            }
        },
        methods: {
          changeItem(ip, port) {
            this.formData.ProtocolInfo.Ip = ip
            this.formData.ProtocolInfo.Port = port
          },
          handleChangeProtocolType(val) {//切换协议类型
            switch (val) {
              case 'modbus-tcp':
              case 'bacnet-ip':
              case 'knx':
              case 'lora':
                break
              case 'opc' :
                break
              case 'mqtt':
              case 'amqp':
                break
              case 'ems-collect':
                break
              case 'common':
                this.formData.ProtocolStandarded = false
                break

            }
            // if (val == 'common') {
            //   this.formData.ProtocolStandarded = false
            // } else {
            //   this.formData.ProtocolStandarded = true
            // }
          },
          getDataSouse() {
            let param = {
              Filters: {
                Id: this.id
              },
              "PageNumber": 1,
              "PageSize": 50,
              "Projection": []
            }
            queryDataSource(param, res => {
              let data = res.Content[0]
              if (!data.ProtocolInfo) {
                //信息点为空时
                data.ProtocolInfo = {
                  "Ip": "", //ip
                  "Port": "",
                  "User": "", //用户名
                  "Password": "", //密码
                  "ProgId": "", //progId
                }
              } else {
                //有信息点时
                this.ProtocolInfo = JSON.stringify(data.ProtocolInfo)
              }
              this.formData = data
              if(data) {

              }
              data.ProtocolType = data.ProtocolType == '其他' ? 'common':data.ProtocolType
              this.handleChangeProtocolType( data.ProtocolType)
              console.log(this.formData, "formData")
            })
          },
          btnClick() {
                console.log(this.formData, "form")
                let param = tools.deepCopy(this.formData)
                tools.delObjKey(param, "CreateTime")
                tools.delObjKey(param, "LastUpdate")
                if(param.ProtocolType == 'common'){
                    try{
                        let ProtocolInfo = JSON.parse(this.ProtocolInfo)
                        param.ProtocolInfo = ProtocolInfo
                    } catch (err) {
                        this.$message.error("属性详情格式错误！")
                        return false
                    }
                }
                if (!!this.id) {
                    console.log(param.ProtocolInfo.Port)
                    if (param.ProtocolInfo.hasOwnProperty("Port") && param.ProtocolInfo.Port == "") {
                        delete param.ProtocolType.Port
                    }
                    updateDataSource({
                        Content: [param],
                        Projection: []
                    }, res => {
                        console.log(res, 'res')
                        this.$router.push({
                            path: '/point/pointsetting'
                        })
                        this.$message.success("更新成功！")
                    })
                } else {
                    // param.ProjectId = this.projectId
                    console.log(param, "param")
                    createDataSource(param, res => {
                        console.log(res)
                        this.$router.push({
                            path: '/point/pointsetting'
                        })
                        this.$message.success("创建成功！")
                    })
                }
            },
            deletePort() {
                this.formData.ProtocolInfo.Port = ""
            }
        },
        watch: {
            projectId(){
                this.$router.push({
                    path: '/point/pointsetting'
                })
            }
        }
    }
</script>
<style lang="scss">
    .margin-view {
        height: 60px;
    }
    .btn-view {
        overflow: hidden;
        .btn {
            float: right;
            margin-right: 40px;
        }
    }
    .content-view {
        width: 928px;
        margin: auto;
        .edit-textarea {
            margin: 8px 0 22px 0;
            height: 117px;
            textarea {
                height: 100%;
                background-color: #EEFAFF;
            }
        }
    }
</style>
