<template>
  <div class="fullheight single-padding">
    <ht-table
      @load="loadData"
      @row-dblclick="row => showDialog(row.id)"
      :data="data"
      :pageResult="pageResult"
      :selection="false"
      :selectable="false"
      quick-search-props="modelName"
      :default-sorter="[{direction: 'ASC', property: 'sn'}]"
      :show-export="false"
      :show-custom-column="false"
      ref="htTable"
    >
      <template v-slot:toolbar>
        <el-button
          size="small"
          @click="showDialog()"
          icon="el-icon-plus"
          type="primary"
          >添加</el-button
        >
        <!-- <ht-delete-button
          url="${cssc}/biz/model/modelInfo/v1/"
          :htTable="$refs.htTable"
          >删除</ht-delete-button
        > -->
        <el-button
          size="small"
          type="primary"
          plain
          @click="save()"
          icon="el-icon-finished"
          >保存模型排序</el-button
        >
      </template>
      <template>
        <ht-table-column
          prop="modelName"
          label="模型名称"
          :show-overflow-tooltip="true"
        >
        </ht-table-column>
        <ht-table-column
          prop="modelType"
          label="模型类型"
          width="120"
          :sortable="true"
          :filters="modelTypeList"
        >
          <template v-slot="{row}">
            <el-tag v-if="row.modelType == 'Python'">Python </el-tag>
            <el-tag type="success" v-if="row.modelType == 'Matlab'"
              >Matlab
            </el-tag>
          </template>
        </ht-table-column>
        <ht-table-column
          prop="modelClass"
          label="模型分类"
          width="120"
          :sortable="true"
          :filters="options.zy"
        >
          <template v-slot="{row}">
            <el-tag type="warning">{{ row.modelClass }} </el-tag>
          </template>
        </ht-table-column>
        <!--  {{ row.modelServerIp?row.modelServerIp:'' + row.modelServerPort?':'+ row.modelServerPort:''}} -->
        <ht-table-column
          prop="modelServerIp"
          label="模型部署地址"
          :show-overflow-tooltip="true"
        >
          <template v-slot="{row}">
            {{ row.modelServerIp
            }}{{ row.modelServerPort ? `:${row.modelServerPort}` : '' }}
          </template>
        </ht-table-column>
        <ht-table-column
          prop="fileIsUpload"
          label="是否上传算法文件"
          width="140"
          :show-overflow-tooltip="true"
        >
          <template v-slot="{row}">
            <el-tag type="danger" v-if="row.fileIsUpload == 0">否</el-tag>
            <el-tag type="success" v-if="row.fileIsUpload == 1">是</el-tag>
          </template>
        </ht-table-column>

        <!-- <ht-table-column
          label="计算频率"
          width="100"
          :show-overflow-tooltip="true"
        >
          <template v-slot="{row}">
            <div v-if="row.modelRateUnit == 'm'">
              {{ row.modelRate + '分钟' }}
            </div>
            <div v-if="row.modelRateUnit == 'h'">
              {{ row.modelRate + '小时' }}
            </div>
            <div v-if="row.modelRateUnit == 'd'">
              {{ row.modelRate + '天' }}
            </div>
            <div v-if="row.modelRateUnit == 'w'">
              {{ row.modelRate + '周' }}
            </div>
            <div v-if="row.modelRateUnit == 'M'">
              {{ row.modelRate + '月' }}
            </div>
            <div v-if="row.modelRateUnit == 'Y'">
              {{ row.modelRate + '年' }}
            </div>
          </template>
        </ht-table-column>
        <ht-table-column
          prop="state"
          label="运行状态"
          :show-overflow-tooltip="true"
          width="80"
        >
          <template v-slot="{row}">
            <el-tag type="danger" v-if="row.state == ''">未启动</el-tag>
            <el-tag type="warning" v-if="row.state == 'PAUSED'">暂停</el-tag>
            <el-tag type="success" v-if="row.state == 'NORMAL'">启动</el-tag>
          </template>
        </ht-table-column> -->
        <ht-table-column
          prop="resultIsCreate"
          label="是否创建结果表"
          width="140"
        >
          <template v-slot="{row}">
            <el-tag type="danger" v-if="row.resultIsCreate == 0">否</el-tag>
            <el-tag type="success" v-if="row.resultIsCreate == 1">是</el-tag>
          </template>
        </ht-table-column>
        <ht-table-column prop="taosIsCreate" label="是否创建采集表" width="140">
          <template v-slot="{row}">
            <el-tag type="danger" v-if="row.taosIsCreate == 0">否</el-tag>
            <el-tag type="success" v-if="row.taosIsCreate == 1">是</el-tag>
          </template>
        </ht-table-column>

        <ht-table-column
          prop="sn"
          label="模型排序"
          width="100"
          :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>
        <ht-table-column
          label="操作"
          width="145"
          :show-overflow-htoolitp="true"
        >
          <template v-slot="{row}">
            <el-dropdown
              size="mini"
              split-button
              @command="handleCommand"
              @click="
                handleCommand({
                  id: row.id,
                  ename: 'ModelFan',
                  code: row.modelCode,
                  open: true
                })
              "
              ><span
                :command="{
                  id: row.id,
                  ename: 'ModelFan',
                  code: row.modelCode
                }"
              >
                <i class="el-icon-connection"></i>关联机组
              </span>
              <el-dropdown-menu slot="dropdown">
                <!-- <el-dropdown-item
                  icon="el-icon-search"
                  :command="{
                    id: row.id,
                    ename: 'ModelLog',
                    open: true
                  }"
                  >日志查询</el-dropdown-item
                > -->
                <el-dropdown-item
                  icon="el-icon-upload2"
                  :command="{
                    id: row.id,
                    code: row.modelCode,
                    ename: 'ParamInConfig',
                    open: true
                  }"
                  >入参配置</el-dropdown-item
                >
                <el-dropdown-item
                  icon="el-icon-download"
                  :command="{
                    id: row.id,
                    code: row.modelCode,
                    ename: 'ParamOutConfig',
                    open: true
                  }"
                  >出参配置</el-dropdown-item
                >
                <el-dropdown-item
                  icon="el-icon-document-add"
                  :command="{
                    id: row.id,
                    ename: 'uploadFile',
                    open: true
                  }"
                  >上传算法文件</el-dropdown-item
                >
                <el-dropdown-item
                  icon="el-icon-document-add"
                  v-if="row.taosIsCreate == 0"
                  :command="{
                    id: row.id,
                    type: 'taos',
                    open: false
                  }"
                  >创建采集表</el-dropdown-item
                >
                <el-dropdown-item
                  icon="el-icon-document-add"
                  v-if="row.resultIsCreate == 0"
                  :command="{
                    id: row.id,
                    type: 'result',
                    open: false
                  }"
                  >创建结果表</el-dropdown-item
                >
                <!-- 需存在算法文件且有采集表结果表才能创建模型任务 -->
                <el-dropdown-item
                  v-if="
                    row.fileIsUpload == 1 &&
                      row.resultIsCreate == 1 &&
                      row.taosIsCreate == 1
                  "
                  icon="el-icon-setting"
                  :command="{
                    id: row.id,
                    ename: 'ModelTask',
                    open: true
                  }"
                  >模型任务</el-dropdown-item
                >
                <el-dropdown-item
                  icon="el-icon-delete"
                  :command="{
                    id: row.id,
                    ename: 'delete'
                  }"
                >
                  删除
                </el-dropdown-item>
                <!-- <el-dropdown-item
                  icon="el-icon-caret-right"
                  v-if="
                    row.resultIsCreate &&
                      row.taosIsCreate &&
                      row.state != 'NORMAL'
                  "
                  :command="{
                    id: row.id,
                    state: row.state,
                    open: false
                  }"
                  >启动</el-dropdown-item
                >

                <el-dropdown-item
                  icon="el-icon-video-pause"
                  v-if="
                    row.resultIsCreate &&
                      row.taosIsCreate &&
                      row.state == 'NORMAL'
                  "
                  :command="{
                    id: row.id,
                    state: row.state,
                    open: false
                  }"
                  >暂停</el-dropdown-item
                > -->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </ht-table-column>
      </template>
    </ht-table>
    <common-dialog
      width="600px"
      title="上传算法文件"
      class="sp-manager__dialog"
      :visible="uploadVisible"
      destroy-on-close
    >
      <el-form ref="form" label-width="150px">
        <ht-form-item label="算法文件">
          <el-upload
            style="display: inline-block;"
            :action="importUrl"
            :on-success="hadleUploadResult"
            :on-error="hadleUploadResult"
            :headers="uploadHeaders"
            :on-exceed="onExceed"
            accept=".zip"
            :before-upload="beforeUpload"
            :limit="1"
            :data="uploadData"
            :auto-upload="false"
            ref="upload"
          >
            <el-button size="small" icon="el-icon-upload"
              >选择zip文件</el-button
            >
          </el-upload>
        </ht-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitImport"
          element-loading-text="拼命上传中"
          v-loading.fullscreen.lock="fullscreenLoading"
          >确 定</el-button
        >
        <el-button @click="cancelConfirm()">取 消</el-button>
      </div>
    </common-dialog>
    <common-dialog
      width="1000px"
      title="计算模型基础信息"
      class="sp-manager__dialog"
      :visible="dialogVisible"
      :before-close="beforeCloseDialog"
      destroy-on-close
    >
      <el-form v-form data-vv-scope="BizModelInfoForm">
        <el-row>
          <el-col :span="12">
            <ht-form-item label="模型编码" label-width="120px">
              <ht-input
                style="width: 96%"
                v-model="BizModelInfo.modelCode"
                validate="required"
                :disabled="!!BizModelInfo.id"
                placeholder="请输入模型编码"
              />
            </ht-form-item>
          </el-col>
          <el-col :span="12">
            <ht-form-item label="模型名称" label-width="120px">
              <ht-input
                v-model="BizModelInfo.modelName"
                validate="required"
                style="width:96%"
                placeholder="请输入模型名称"
              />
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <ht-form-item label="模型分类" label-width="120px">
              <ht-select
                style="width: 96%"
                v-model="BizModelInfo.modelClass"
                multiple
                :options="options.zy"
                :remote-method="handleModelClass"
                :validate="{required: true}"
              ></ht-select>
            </ht-form-item>
          </el-col>
          <el-col :span="12">
            <ht-form-item label="模型类型" label-width="120px">
              <ht-radio
                style="width: 100%"
                v-model="BizModelInfo.modelType"
                :options="modelTypeList"
                validate="required"
              />
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <ht-form-item label="模型调用文件地址" label-width="140px">
              <ht-input
                style="width:96%"
                v-model="BizModelInfo.modelMain"
                validate="required"
                placeholder="请输入模型调用文件地址"
              ></ht-input>
            </ht-form-item>
          </el-col>
          <el-col :span="12">
            <ht-form-item label="模型上传地址" label-width="140px">
              <ht-input
                style="width:96%"
                v-model="BizModelInfo.modelUpload"
                validate="required"
                placeholder="请输入模型上传地址"
              ></ht-input>
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <ht-form-item label="参数打包类型" label-width="140px">
              <ht-radio
                style="width: 100%"
                v-model="BizModelInfo.paramForm"
                :options="[
                  {key: 'csv', value: 'csv'},
                  {key: 'json', value: 'json'}
                ]"
                validate="required"
              />
            </ht-form-item>
          </el-col>
          <el-col :span="12">
            <ht-form-item label="参数采集频率" label-width="140px">
              <ht-select
                style="width: 96%"
                v-model="BizModelInfo.paramRate"
                :options="[
                  {key: 's', value: '秒级'},
                  {key: 'm', value: '分钟级'},
                  {key: 'h', value: '小时'},
                  {key: 'd', value: '天'}
                ]"
                validate="required"
              />
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-row>
              <el-col :span="19">
                <ht-form-item label="参数使用频率" label-width="140px">
                  <ht-input
                    type="number"
                    :min="0"
                    v-model="BizModelInfo.paramUseRate"
                    validate="required"
                  />
                </ht-form-item>
              </el-col>
              <el-col :span="5">
                <ht-form-item label-width="0px">
                  <ht-select
                    style="width: 85px"
                    v-model="BizModelInfo.paramUseRateUnit"
                    :options="[
                      {key: 'm', value: '分钟'},
                      {key: 'h', value: '小时'},
                      {key: 'd', value: '天'},
                      {key: 'w', value: '周'},
                      {key: 'M', value: '月'},
                      {key: 'Y', value: '年'}
                    ]"
                    validate="required"
                  ></ht-select>
                </ht-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <ht-form-item label="参数存放地址" label-width="140px">
              <ht-input
                style="width: 96%"
                v-model="BizModelInfo.paramPath"
                validate="required"
                placeholder="请输入参数存放地址"
              />
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <ht-form-item label="部署服务器IP" label-width="140px">
              <ht-input
                style="width: 96%"
                :min="0"
                v-model="BizModelInfo.modelServerIp"
                validate="required"
                placeholder="请输入部署服务器IP"
              />
            </ht-form-item>
          </el-col>
          <el-col :span="12">
            <ht-form-item label="部署服务器端口" label-width="140px">
              <ht-input
                style="width: 96%"
                :min="0"
                v-model="BizModelInfo.modelServerPort"
                validate="required"
                placeholder="请输入部署服务器端口"
              />
            </ht-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <ht-form-item label="部署服务器用户名" label-width="140px">
              <ht-input
                style="width: 96%"
                :min="0"
                v-model="BizModelInfo.modelServerUser"
                validate="required"
                placeholder="请输入部署服务器用户名"
              />
            </ht-form-item>
          </el-col>
          <el-col :span="12">
            <ht-form-item label="部署服务器密码" label-width="140px">
              <ht-input
                style="width: 96%"
                :min="0"
                v-model="BizModelInfo.modelServerPassword"
                validate="required"
                placeholder="请输入部署服务器密码"
              />
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row>
          <ht-form-item label="模型说明" label-width="140px">
            <ht-input
              style="width: 98%"
              type="textarea"
              v-model="BizModelInfo.memo"
            />
          </ht-form-item>
        </el-row>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button type="success" @click="testConnected"
          >服务器链接测试</el-button
        >
        <ht-submit-button
          url="${cssc}/biz/model/modelInfo/v1/"
          :model="BizModelInfo"
          :request-method="saveMethod"
          scope-name="BizModelInfoForm"
          @after-save-data="afterSaveData"
          >保存</ht-submit-button
        >
        <el-button @click="beforeCloseDialog">取消</el-button>
      </div>
    </common-dialog>
  </div>
</template>
<script>
import req from '@/request.js'
export default {
  name: 'model-info-manager',
  data() {
    return {
      dialogVisible: false,
      data: [],
      pageResult: {
        page: 1,
        pageSize: 50,
        total: 0
      },
      BizModelInfo: {
        modelType: 'Python', //模型类型
        modelClass: 'Scada', //模型分类
        modelRateUnit: 'm', //模型时间单位
        modelMode: '1', //模型计算方式
        paramForm: 'csv', //参数打包类型
        paramRate: 'm', //参数采集频率
        paramUseRateUnit: 'm' //参数使用频率
      },
      saveMethod: 'POST',
      modelTypeList: [
        {key: 'Python', value: 'Python', text: 'Python'},
        {key: 'Matlab', value: 'Matlab', text: 'Matlab'}
      ],
      options: {
        zy: null,
        zy2: [
          {key: 'Scada', value: 'Scada'},
          {key: 'CMS', value: 'CMS'},
          {key: 'PLC', value: 'PLC'}
        ]
      },
      snObj: {},
      // 算法文件上传
      uploadVisible: false,
      fullscreenLoading: false,
      uploadData: {
        modelId: ''
      }
    }
  },
  computed: {
    importUrl: function() {
      return window.context.cssc + '/biz/model/modelInfo/v1/importModel'
    },
    uploadHeaders: function(mapState) {
      return {
        Authorization: 'Bearer ' + this.$store.state.login.currentUser.token
      }
    }
  },
  mounted() {
    this.$validator = this.$root.$validator
  },
  methods: {
    // 算法文件上传
    hadleUploadResult(response) {
      this.fullscreenLoading = false
      if (response.state) {
        this.$message.success(response.message)
        this.uploadVisible = false
        this.$refs.htTable.load()
      } else {
        this.$message.error(response.message + '：' + response.value)
      }
    },
    beforeUpload(file) {
      if (!file.name.endsWith('.zip')) {
        this.$message.warning('只能上传zip文件!')
        return false
      }
      this.fullscreenLoading = true
    },
    onExceed() {
      this.$message.warning('只能选择一个zip文件!')
    },
    submitImport() {
      if (
        !this.$refs.upload.uploadFiles ||
        this.$refs.upload.uploadFiles.length == 0
      ) {
        this.$message.warning('请选择要上传的zip文件!')
        return false
      }
      this.$refs.upload.submit()
    },
    cancelConfirm() {
      this.$refs.upload.clearFiles()
      this.uploadVisible = false
      this.$refs.upload.uploadFiles = []
    },

    // 算法文件上传
    testConnected() {
      let data = this.qs.stringify({
        host: this.BizModelInfo.modelServerIp,
        password: this.BizModelInfo.modelServerPassword,
        port: this.BizModelInfo.modelServerPort,
        username: this.BizModelInfo.modelServerUser
      })
      req
        .request({
          url: '${cssc}/biz/model/modelInfo/v1/sshIsConnected',
          data: data,
          headers: {
            'Content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST'
        })
        .then(res => {
          if (res.data.state) {
            this.$message({
              type: 'success',
              message: res.data.message
            })
          }
        })
        .catch(err => {
          this.$message({
            type: 'warning',
            message: err
          })
        })
    },

    handleCommand(command) {
      //启动、暂停按钮
      if (command.open) {
        if (command.ename == 'ModelFan') {
          this.$router.push({
            path: `ModelFan/${command.id}/${command.code}`
          })
        } else if (command.ename == 'ParamInConfig') {
          this.$router.push({
            path: `ParamInConfig/${command.id}/${command.code}`
          })
        } else if (command.ename == 'ParamOutConfig') {
          this.$router.push({
            path: `ParamOutConfig/${command.id}/${command.code}`
          })
        } else if (command.ename == 'ModelTask') {
          this.$router.push({path: `ModelTask/${command.id}`})
        } else if (command.ename == 'uploadFile') {
          this.uploadVisible = true
          this.uploadData.modelId = command.id
        }
      } else {
        if (command.type) {
          let id = this.qs.stringify({id: command.id})
          let headersUrlencoded = {
            'Content-type': 'application/x-www-form-urlencoded'
          }
          let url = '${cssc}/biz/model/modelInfo/v1/creatTaosTable'
          if (command.type == 'result') {
            url = '${cssc}/biz/model/modelInfo/v1/creatResultTable'
          }
          req
            .request({
              url: url,
              data: id,
              headers: headersUrlencoded,
              method: 'POST'
            })
            .then(res => {
              if (res.data.state) {
                this.$message({
                  type: 'success',
                  message: res.data.message
                })
                this.$refs.htTable.load()
              }
            })
            .catch(err => {
              this.$message({
                type: 'warning',
                message: err
              })
            })
        }
        if (command.ename == 'delete') {
          this.$confirm('是否删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          })
            .then(() => {
              this.$http
                .remove('${cssc}/biz/model/modelInfo/v1/' + command.id)
                .then(res => {
                  if (res.data.state) {
                    this.$message({
                      type: 'success',
                      message: '删除成功'
                    })
                    this.$refs.htTable.load()
                  }
                })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
            })
        }
      }
    },
    handleChange(row, val) {
      this.snObj[row.id] = val
    },
    save() {
      this.$http
        .post('${cssc}/biz/model/modelInfo/v1/updateSequence/', this.snObj)
        .then(res => {
          this.$refs.htTable.load()
        })
    },
    handleModelClass(query) {
      let _me = this
      return new Promise((resolve, reject) => {
        _me.options.zy = _me.options.zy2
        resolve()
      })
    },
    showDialog(id) {
      if (id) {
        this.saveMethod = 'PUT'
        this.$http.get('${cssc}/biz/model/modelInfo/v1/' + id).then(
          resp => {
            this.BizModelInfo = resp.data
            this.dialogVisible = true
          },
          error => {
            reject(error)
          }
        )
      } else {
        this.saveMethod = 'POST'
        this.dialogVisible = true
      }
    },
    beforeCloseDialog() {
      this.BizModelInfo = {
        modelType: 'Python',
        modelClass: 'Scada',
        modelRateUnit: 'm',
        modelMode: '1',
        paramForm: 'csv',
        paramRate: 'm',
        paramUseRateUnit: 'm'
      }
      this.dialogVisible = false
    },
    loadData(param, cb) {
      this.$http
        .post('${cssc}/biz/model/modelInfo/v1/query', 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())
    },
    afterSaveData() {
      setTimeout(() => {
        this.beforeCloseDialog()
        this.$refs.htTable.load()
      }, 500)
    }
  }
}
</script>

<style lang="scss" scoped>
.sp-manager__dialog /deep/ .el-dialog > .el-dialog__body {
  height: calc(100% - 170px);
}
.el-dropdown {
  vertical-align: top;
}
.el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
/deep/ .el-input-number--small {
  width: 240px;
}
/deep/ .el-dialog__body {
  padding: 20px 20px 10px;
}
</style>
