<template>
  <div class="single-padding">
    <el-page-header
      @back="goBack"
      content="入参配置"
      style="margin-bottom: 20px"
    >
    </el-page-header>
    <div style="width: 100%; height: calc(100% - 44px)">
      <ht-table
        @load="loadData"
        @row-dblclick="row => showDialog(row.id)"
        :data="data"
        :pageResult="pageResult"
        :selection="true"
        quick-search-props="paramCode,paramName,paramClass"
        :default-sorter="[
          {direction: 'ASC', property: 'paramType'},
          {direction: 'ASC', property: 'sn'}
        ]"
        :show-export="false"
        :show-custom-column="false"
        ref="htTable"
      >
        <template v-slot:toolbar>
          <el-button
            size="small"
            @click="showDialog2()"
            icon="el-icon-plus"
            type="primary"
            >添加</el-button
          >
          <ht-delete-button
            url="${cssc}/biz/model/modelInfo/v1/modelParams/deleteModelParams"
            :htTable="$refs.htTable"
            >删除</ht-delete-button
          >
          <el-button
            size="small"
            type="primary"
            plain
            @click="saveOrder"
            icon="el-icon-finished"
            >保存排序</el-button
          >
        </template>
        <template>
          <ht-table-column
            prop="paramCode"
            label="参数编码"
            :sortable="true"
            :show-overflow-tooltip="true"
          >
          </ht-table-column>
          <ht-table-column
            prop="paramName"
            label="参数名称"
            :sortable="true"
            :show-overflow-tooltip="true"
          >
          </ht-table-column>
          <ht-table-column
            prop="paramType"
            label="参数类型"
            :sortable="true"
            :show-overflow-tooltip="true"
          >
            <template v-slot="{row}">
              <div v-if="row.paramType == 'param'">入参</div>
            </template>
          </ht-table-column>
          <ht-table-column
            prop="paramClass"
            label="参数类别"
            :sortable="true"
            :show-overflow-tooltip="true"
            :filters="class2"
          >
            <template v-slot="{row}">
              <el-tag v-if="row.paramClass == 'Scada'">Scada </el-tag>
              <el-tag type="success" v-if="row.paramClass == 'CMS'"
                >CMS
              </el-tag>
              <el-tag type="warning" v-if="row.paramClass == 'PLC'"
                >PLC
              </el-tag>
            </template>
          </ht-table-column>

          <ht-table-column
            prop="paramNature"
            label="参数性质"
            :sortable="true"
            :show-overflow-tooltip="true"
            :filters="[{value: 1, text: '固定'}, {value: 2, text: '动态'}]"
          >
            <template v-slot="{row}">
              <el-tag type="danger" v-if="row.paramNature == 1">固定</el-tag>
              <el-tag type="warning" v-if="row.paramNature == 2">动态</el-tag>
            </template>
          </ht-table-column>
          <ht-table-column
            prop="paramDataType"
            label="数据类型"
            :sortable="true"
            :show-overflow-tooltip="true"
            :filters="dataType"
          >
            <template v-slot="{row}">
              <div v-if="row.paramDataType == 'B'">布尔型</div>
              <div v-if="row.paramDataType == 'I'">整型</div>
              <div v-if="row.paramDataType == 'F'">浮点型</div>
              <div v-if="row.paramDataType == 'S'">字符串</div>
              <div v-if="row.paramDataType == 'D'">日期</div>
              <div v-if="row.paramDataType == 'T'">时间</div>
            </template>
          </ht-table-column>

          <ht-table-column
            prop="sn"
            label="排序号"
            width="120"
            :show-overflow-tooltip="true"
          >
            <template v-slot="{row}">
              <el-input-number
                style="width: 100%"
                v-model="row.sn"
                :controls="false"
                @change="(val, old) => handleChange(row, val)"
                :min="0"
              ></el-input-number>
            </template>
          </ht-table-column>
        </template>
      </ht-table>
    </div>
    <!-- 添加弹框 -->
    <common-dialog
      width="900px"
      title="入参配置信息"
      class="sp-manager__dialog add-dialog "
      :visible="dialogVisible2"
      :before-close="beforeCloseDialog2"
      destroy-on-close
    >
      <el-form v-form data-vv-scope="BizParamAdd">
        <el-row>
          <el-col :span="12">
            <ht-form-item label="参数性质" label-width="80">
              <ht-select
                v-model="paramInfo.paramNature"
                :options="[{key: 1, value: '固定'}, {key: 2, value: '动态'}]"
                :validate="{required: true}"
                @change="changeparamInfo"
                style="width:200px"
              ></ht-select>
            </ht-form-item>
          </el-col>
          <el-col :span="12">
            <ht-form-item label="参数类别">
              <ht-select
                v-model="paramInfo.paramClass"
                :options="class2"
                :props="{key: 'value', value: 'text'}"
                :validate="{required: true}"
                @change="changeParamClass"
                style="width: 200px"
              ></ht-select>
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-bottom:10px">
          <el-col :span="24">
            <el-button
              size="mini"
              @click="showDialog3"
              icon="el-icon-plus"
              type="primary"
              v-if="paramInfo.paramNature == 2"
              >批量选择</el-button
            >
            <el-button
              size="mini"
              icon="el-icon-plus"
              type="primary"
              @click="handleAdd"
              v-if="paramInfo.paramNature == 1"
              >添加</el-button
            >
            <el-popconfirm title="确定删除吗？" @onConfirm="handleDelete()">
              <el-button
                slot="reference"
                type="danger"
                size="mini"
                icon="el-icon-delete"
                >删除</el-button
              >
            </el-popconfirm>
          </el-col>
        </el-row>
        <el-table
          class="table2"
          ref="htTable2"
          :data="data2"
          style="width: 100%"
          border
          height="calc(100% - 76px)"
          :header-cell-style="{
            background: '#eee',
            color: '#3c4353'
          }"
        >
          <el-table-column type="selection" align="center"> </el-table-column>
          <el-table-column label="参数编码" align="center">
            <template slot-scope="scope">
              <div v-if="paramInfo.paramNature == 2">
                {{ scope.row.paramCode }}
              </div>
              <ht-input
                v-model="scope.row.paramCode"
                :validate="{
                  required: true,
                  method: {
                    callback: (value, args) =>
                      checkRepeat(value, 'paramCode', scope.row),
                    message: '参数编码重复'
                  }
                }"
                placeholder="请输入参数编码"
                :maxlength="50"
                :showWordLimit="true"
                v-if="paramInfo.paramNature == 1"
              ></ht-input>
            </template>
          </el-table-column>
          <el-table-column prop="paramName" label="参数名称" align="center">
            <template slot-scope="scope">
              <div v-if="paramInfo.paramNature == 2">
                {{ scope.row.paramName }}
              </div>
              <ht-input
                v-model="scope.row.paramName"
                validate="required"
                autocomplete="off"
                placeholder="请输入参数名称"
                :maxlength="100"
                :showWordLimit="true"
                v-else
              ></ht-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="paramDataType"
            label="数据类型"
            show-overflow-tooltip
            align="center"
            :validate="{required: true}"
          >
            <template slot-scope="scope">
              <div v-if="paramInfo.paramNature == 2">
                <div v-if="scope.row.paramDataType == 'B'">布尔型</div>
                <div v-if="scope.row.paramDataType == 'I'">整型</div>
                <div v-if="scope.row.paramDataType == 'F'">浮点型</div>
                <div v-if="scope.row.paramDataType == 'S'">字符串</div>
                <div v-if="scope.row.paramDataType == 'D'">日期</div>
                <div v-if="scope.row.paramDataType == 'T'">时间</div>
              </div>
              <ht-select
                v-else
                v-model="scope.row.paramDataType"
                :options="dataType"
                :props="{key: 'value', value: 'text'}"
              ></ht-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="paramValue"
            label="参数值"
            show-overflow-tooltip
            align="center"
            v-if="paramInfo.paramNature == 1"
          >
            <template slot-scope="scope">
              <ht-input
                v-model="scope.row.paramValue"
                placeholder="请输入参数值"
              ></ht-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" style="text-align: center">
        <ht-submit-button
          url="${cssc}/biz/model/modelInfo/v1/modelParams/insertBatch"
          :model="data2"
          :request-method="saveMethod"
          @before-save-data="beforeSaveData"
          @after-save-data="afterSaveData"
          scope-name="BizParamAdd"
          >保存</ht-submit-button
        >
        <el-button @click="beforeCloseDialog2">取消</el-button>
      </div>
    </common-dialog>
    <!-- 选择点位信息弹框 -->
    <common-dialog
      width="900px"
      title="选择参数"
      class="sp-manager__dialog dialog-pointer"
      :visible="dialogVisible3"
      :before-close="beforeCloseDialog3"
      destroy-on-close
    >
      <ht-table
        style="height: 100%"
        @load="tableData3"
        :data="data3"
        :pageResult="pageResult3"
        quick-search-props="pointName,varName"
        :default-sorter="[{direction: 'ASC', property: 'sn'}]"
        selection="true"
        :show-export="false"
        :show-custom-column="false"
        ref="htTable3"
      >
        <template>
          <ht-table-column
            prop="pointName"
            label="点位名称"
            :show-overflow-tooltip="true"
          ></ht-table-column>
          <ht-table-column
            prop="varName"
            label="点位编码"
            :show-overflow-tooltip="true"
          ></ht-table-column>
          <ht-table-column
            prop="pointType"
            label="点位类型"
            :show-overflow-tooltip="true"
          >
            <template v-slot="{row}">
              <el-tag v-if="row.pointType == 2">机组点位 </el-tag>
            </template>
          </ht-table-column>
        </template>
      </ht-table>
      <div slot="footer" style="text-align: center">
        <el-button type="primary" @click="confirmPoint">确定</el-button>
        <el-button @click="beforeCloseDialog3">取消</el-button>
      </div>
    </common-dialog>
    <!-- 修改弹框 -->
    <common-dialog
      width="800px"
      title="参数配置信息"
      class="sp-manager__dialog"
      :visible="dialogVisible"
      :before-close="beforeCloseDialog"
      destroy-on-close
    >
      <el-form v-form data-vv-scope="BizParamForm">
        <ht-form-item label="参数类别">
          <ht-select
            v-model="paramInfo.paramClass"
            :options="class2"
            :props="{key: 'value', value: 'text'}"
            :validate="{required: true}"
          ></ht-select>
        </ht-form-item>
        <ht-form-item label="参数编码">
          <ht-input v-model="paramInfo.paramCode" validate="required" />
        </ht-form-item>
        <ht-form-item label="参数名称">
          <ht-input v-model="paramInfo.paramName" validate="required" />
        </ht-form-item>
        <ht-form-item label="参数性质">
          <ht-select
            v-model="paramInfo.paramNature"
            :options="paramNatureType"
            :props="{key: 'value', value: 'text'}"
            :validate="{required: true}"
          ></ht-select>
        </ht-form-item>
        <ht-form-item label="数据类型">
          <ht-select
            v-model="paramInfo.paramDataType"
            :options="dataType"
            :props="{key: 'value', value: 'text'}"
            :validate="{required: true}"
          ></ht-select>
        </ht-form-item>
        <ht-form-item label="参数值" v-if="paramInfo.paramNature === 1">
          <ht-input v-model="paramInfo.paramValue" />
        </ht-form-item>
        <ht-form-item label="数据说明">
          <ht-input type="textarea" v-model="paramInfo.paramMemo" />
        </ht-form-item>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button type="primary" @click="saveUpdateParam">保存</el-button>
        <el-button @click="beforeCloseDialog">取消</el-button>
      </div>
    </common-dialog>
  </div>
</template>
<script>
import utils from '@/hotent-ui-util.js'
import req from '@/request.js'
export default {
  data() {
    return {
      data3: [],
      selectData2: [],
      data2: [],
      dialogVisible3: false,
      dialogVisible2: false,
      dialogVisible: false,
      pageResult3: {
        page: 1,
        pageSize: 50,
        total: 0
      },
      data: [],
      pageResult: {
        page: 1,
        pageSize: 50,
        total: 0
      },

      paramInfo: {
        modelId: this.$route.params.id,
        modelCode: this.$route.params.code,
        paramType: 'param',
        paramClass: 'Scada',
        paramDataType: 'B',
        paramNature: 2,
        paramMemo: 0,
        paramValue: ''
      },
      saveMethod: 'POST',
      class2: [
        {value: 'Scada', text: 'Scada'},
        {value: 'CMS', text: 'CMS'},
        {value: 'PLC', text: 'PLC'}
      ],
      dataType: [
        {value: 'B', text: '布尔型'},
        {value: 'I', text: '整型'},
        {value: 'F', text: '浮点型'},
        {value: 'S', text: '字符串'},
        {value: 'D', text: '日期'},
        {value: 'T', text: '时间'}
      ],
      paramNatureType: [{value: 1, text: '固定'}, {value: 2, text: '动态'}],
      type: [{value: 'param', text: '入参'}, {value: 'result', text: '出参'}],
      snObj: {},
      selectionPoint: [],
      multipleSelection: []
    }
  },
  mounted() {
    this.$validator = this.$root.$validator
  },

  methods: {
    // 提交验证
    async beforeSaveData() {
      if (this.data2.length) {
        let TempArr = [...this.data2]
        TempArr.forEach(item => {
          delete item.key
        })
      }
    },
    afterSaveData() {
      setTimeout(() => {
        this.beforeCloseDialog2()
        this.$refs.htTable.load()
      }, 500)
    },
    // 子表的选择回调
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 子表验证
    checkRepeat(value, column, currentItem) {
      return new Promise(resolve => {
        let Temp = this.data2.filter(item => item.key != currentItem.key)
        if (Temp.length) {
          Temp.forEach(item => {
            if (item[column] == value) {
              resolve(false)
            }
          })
          resolve(true)
        } else {
          resolve(true)
        }
      })
    },
    //监听切换参数性质，之前的数据列表清空
    changeparamInfo() {
      if (this.paramInfo.paramNature == 1 || this.paramInfo.paramNature == 2) {
        this.selectData2 = []
        this.data2 = []
      }
    },
    //参数性质是固定时，添加表格行列
    handleAdd() {
      let length = this.data2.length
      if (
        this.paramInfo.paramClass == 'Scada' &&
        this.paramInfo.paramNature == 1
      ) {
        this.data2.push({
          ...this.paramInfo,
          key: new Date().getTime() + length
        })
      } else {
        this.$message.warning('提示 :   正在建设中  !')
      }
    },
    //监听切换参数类别，之前的数据列表清空
    changeParamClass() {
      let paramClass = this.paramInfo.paramClass
      if (paramClass == 'Scada') {
        this.selectData2 = []
        this.data2 = []
      } else if (paramClass == 'SMC') {
        this.selectData2 = []
        this.data2 = []
      } else {
        this.selectData2 = []
        this.data2 = []
      }
    },
    //过滤
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },

    getData2() {
      let obj = []
      this.selectData2.forEach(item => {
        let select = {
          modelCode: this.$route.params.code,
          modelId: this.$route.params.id,
          paramClass: this.paramInfo.paramClass,
          paramCode: item.varName,
          paramDataType: item.dataType,
          paramMemo: this.paramInfo.paramMemo,
          paramName: item.pointName,
          paramType: 'param',
          paramNature: this.paramInfo.paramNature
        }
        obj.push(select)
      })
      this.data2 = obj
    },
    //删除参数配置
    handleDelete() {
      //选中的数据
      let val = this.$refs.htTable2.selection
      //如果未选中，弹出提示框
      if (!val.length) {
        this.$message.warning('请选择要删除的数据')
        return
      } else {
        let data = this.selectData2
        for (var i = 0; i < data.length; i++) {
          val.forEach(item => {
            if (item.paramCode == data[i].varName) {
              data.splice(i, 1)
            }
          })
        }
      }
      this.getData2()
    },
    //确定选择
    confirmPoint() {
      let newData = utils.deepClone(this.$refs.htTable3.$refs.htTable.selection)
      if (!newData || newData.length == 0) {
        this.$message.warning('请至少选择一条参数')
        return
      }
      let ids = []
      this.selectData2.forEach(item => {
        ids.push(item.id)
      })
      let target = newData.filter(item => {
        if (!ids.includes(item.id)) {
          return item
        }
      })
      this.selectData2.push(...target)
      this.getData2()
      this.dialogVisible3 = false
    },
    //选择点位信息选中项
    handlePoint() {
      let row = this.$refs.htTable3.selection
      this.selectionPoint = row
    },
    //点位信息 打开批量添加弹框
    showDialog3() {
      if (
        this.paramInfo.paramClass == 'Scada' &&
        this.paramInfo.paramNature == 2
      ) {
        this.dialogVisible3 = true
      } else if (
        this.paramInfo.paramClass == 'CMS' &&
        this.paramInfo.paramNature == 2
      ) {
        this.$message.warning('提示 :   正在建设中  !')
        //   this.dialogVisible3 = true
      } else if (
        this.paramInfo.paramClass == 'PLC' &&
        this.paramInfo.paramNature == 2
      ) {
        this.$message.warning('提示 :   正在建设中  !')
        //   this.dialogVisible3 = true
      }
    },
    // 添加配置参数弹框
    showDialog2() {
      this.dialogVisible2 = true
    },

    //获取Scada参数点位信息
    tableData3(param, cb) {
      let typeQuery = [
        {
          gourp: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'pointType',
          relation: 'AND',
          value: 2
        }
      ]
      if (param.querys && param.querys.length) {
        param.querys.push(...typeQuery)
      } else {
        param.querys = typeQuery
      }
      this.$http
        .post('${cssc}/biz/base/pointInfo/v1/query', param)
        .then(
          resp => {
            let response = resp.data
            this.data3 = response.rows
            this.pageResult3 = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total
            }
          },
          error => {
            reject(error)
          }
        )
        .finally(() => cb())
    },
    //排序号
    handleChange(row, val) {
      this.snObj[row.id] = val
    },
    //保存排序按钮
    saveOrder() {
      this.$http
        .post(
          '${cssc}/biz/model/modelInfo/v1/modelParams/updateSequence',
          this.snObj
        )
        .then(res => {
          this.$refs.htTable.load()
        })
    },
    //修改按钮
    saveUpdateParam() {
      if (this.paramInfo.paramType == 'result') {
        this.paramInfo.paramClass = ''
      } else if (this.paramInfo.paramClass == '') {
        this.$message.warning('请选择参数类别')
        return
      }
      if (this.paramInfo.paramNature == 2) {
        this.paramInfo.paramValue = ''
      }
      req
        .put('${cssc}/biz/model/modelInfo/v1/modelParams/', this.paramInfo)
        .then(res => {
          if (res.data.state) {
            setTimeout(() => {
              this.$message.success('修改成功')
              this.beforeCloseDialog()
              this.$refs.htTable.load()
            }, 500)
          }
        })
    },
    //修改弹窗
    showDialog(id) {
      this.$http
        .get('${cssc}/biz/model/modelInfo/v1/modelParams/' + id)
        .then(resp => {
          this.paramInfo = resp.data
          this.dialogVisible = true
        })
    },
    resetParam() {
      this.paramInfo = {
        modelId: this.$route.params.id,
        modelCode: this.$route.params.code,
        paramType: 'param',
        paramClass: 'Scada',
        paramDataType: 'B',
        paramNature: 2,
        paramMemo: 0,
        paramValue: ''
      }
    },
    beforeCloseDialog3() {
      this.dialogVisible3 = false
    },
    beforeCloseDialog2() {
      this.dialogVisible2 = false
      this.selectData2 = []
      this.data2 = []
      this.resetParam()
    },

    beforeCloseDialog() {
      this.dialogVisible = false
      this.resetParam()
    },
    //加载数据
    loadData(param, cb) {
      let modelQuery = [
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'modelId',
          relation: 'AND',
          value: this.$route.params.id
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'paramType',
          relation: 'AND',
          value: 'param'
        }
      ]
      if (param.querys && param.querys.length) {
        param.querys.push(...modelQuery)
      } else {
        param.querys = modelQuery
      }
      this.$http
        .post(
          '${cssc}/biz/model/modelInfo/v1/modelParams/sliceQueryParamByModel',
          param
        )
        .then(
          resp => {
            let response = resp.data
            this.data = response.rows
            this.pageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total
            }
          },
          error => {
            reject(error)
          }
        )
        .finally(() => cb())
    },
    // 返回上一页
    goBack() {
      this.$router.push({name: 'ModelInfoManager'})
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-page-header__content {
  font-size: 16px;
}
/deep/ .el-dialog__body {
  padding: 30px 100px;
}
.add-dialog /deep/ .el-dialog__body {
  padding: 10px 20px 0;
  height: 450px;
}
.add-radio {
  line-height: 15px;
}
.table-box {
  width: 100%;
  height: calc(100% - 52px);
  padding-top: 10px;
  border: 1px solid #d6d6d6;
  border-radius: 5px;
}
/deep/ .el-button--mini {
  padding: 6px 5px;
  margin-left: 10px;
}
.dialog-pointer /deep/ .el-dialog__body {
  height: 450px;
  padding: 5px 20px 5px;
}
/deep/ .el-col-22 {
  width: 50%;
}
.table2 /deep/ .is-scrolling-none {
  height: 310px;
}

/deep/ .el-form {
  height: calc(100% - 20px);
}
/deep/ .el-divider {
  background: transparent;
}
</style>
