<template>
  <StatisticsTemplate
    title="产品统计"
    :list="state.modelCount"
  />
  <a-card style="margin-top: 20px;" >
    <a-row justify="space-between" >
      <a-col>
        <a-input-search
          allowClear
          v-model:value="state.queryParams.modelLabel"
          placeholder="请输入产品模型名称"
          enter-button
          @search="getModel"
        />
      </a-col>
      <a-col>
        <a-space>
          <a-button type="primary" @click="openModel('add')" >
            新增
            <template #icon>
              <plus-outlined />
            </template>
          </a-button>
        </a-space>
      </a-col>
    </a-row>

    <a-table
      style="margin-top: 10px;"
      :columns="columns"
      :dataSource="state.dataSource"
      :pagination="state.queryParams"
      :loading="state.loading"
      @change="change"
    >
    <template #name="{ text }">
      <a @click="goDetailPage(text)" >{{ text }}</a>
    </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'id'" >
          <a  @click="goDetailPage(record.id)">{{record.id}}</a>
        </template>
        <template v-if="column.key === 'transportType'" >
          <a-tag  >{{record.transportType}}</a-tag>
        </template>
        <template v-if="column.key === 'payloadType'" >
          <a-tag  color="blue">{{record.payloadType}}</a-tag>
        </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="goDetailPage(record.id)" >查看</a>
              <a  @click="goDevicePage(record.id)">管理</a>
                <a-popconfirm
                  title="确实要删除吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="confirmDel(record.id)"
                >
                  <a href="#">删除</a>
                </a-popconfirm>
            </a-space>
          </template>
        </template>
    </a-table>
  </a-card>

  <a-modal
    :title="modalTitle"
    :open="state.visible"
    ok-text="确定"
    cancel-text="取消"
    @cancel="closeModel"
    @ok="ok"
    destroyOnClose
  >
   <a-form :hideRequiredMark="formOptions.hideRequiredMark" :label-col="{span: 4}" :wrapper-col="{span: 14}">
    <a-form-item v-bind="validateInfos.modelTemplateId">
      <template v-slot:label >
        <a-tooltip>
          <template #title>选择了模型库后不需要再填写产品数据</template>
          <question-circle-outlined /> 模型库
        </a-tooltip>

      </template>
      <a-select allowClear v-model:value="modelRef.modelTemplateId" >
        <a-select-option
          :value="item.id"
          v-for="item in state.modelTemplateList"
          :key="item.id"
        >{{item.templateLabel}}
      </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="模型名称" v-bind="validateInfos.modelLabel">
      <a-input allowClear :disabled="formOptions.disabled" v-model:value="modelRef.modelLabel"  />
    </a-form-item>
    <a-form-item label="协议类型" v-bind="validateInfos.transportType">
      <a-select allowClear :disabled="formOptions.disabled" v-model:value="modelRef.transportType" >
        <a-select-option :value="item.port" v-for="item in state.transport" :key="item.port" >{{item.port}}</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="数据格式" v-bind="validateInfos.payloadType">
      <a-select allowClear :disabled="formOptions.disabled" v-model:value="modelRef.payloadType" >
        <a-select-option :value="item.value" v-for="item in payloadTypeList" :key="item.value" >{{item.label}}</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="设备类型" >
      <a-input allowClear :disabled="formOptions.disabled" v-model:value="modelRef.deviceType"  />
    </a-form-item>
    <a-form-item label="厂商描述">
      <a-textarea  :disabled="formOptions.disabled" v-model:value="modelRef.modelDescription" />
    </a-form-item>
    <a-form-item label="支持视频流">
      <a-switch v-model:checked="modelRef.rts" checked-children="支持" un-checked-children="不支持" />
    </a-form-item>
   </a-form>
  </a-modal>
</template>

<script lang="ts" setup >
import { CommonController, ModelController } from '@/controller/index'
import { onMounted, reactive, watch } from 'vue'
import { computed } from '@vue/reactivity'
import { Form } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import StatisticsTemplate from '@/components/StatisticsTemplate/index.vue'
import { QuestionCircleOutlined } from '@ant-design/icons-vue'
// question-circle-outlined
const columns = [
  {
    title: '产品模型名称',
    dataIndex: 'modelLabel',
    key: 'modelLabel'
  },
  {
    title: '产品模型id',
    dataIndex: 'id',
    key: 'id'
  },
  {
    title: '传输协议',
    dataIndex: 'transportType',
    key: 'transportType'
  },
  {
    title: '数据格式',
    dataIndex: 'payloadType',
    key: 'payloadType'
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    key: 'deviceType'
  },
  {
    title: '模型描述',
    dataIndex: 'modelDescription',
    key: 'modelDescription'
  },
  {
    title: '操作',
    key: 'action'
  }
]

const payloadTypeList = [
  {
    value: 'JSON',
    label: 'JSON'
  },
  {
    value: 'BINARY',
    label: '二进制流'
  }
]

const state = reactive<{
  dataSource: IOT.API.MODEL.ModelDot[],
  modelTemplateList: IOT.API.MODELTEMPLATE.modelTemplate[]
  [key: string]: any
}>({
  loading: false,
  opraState: 'add',
  visible: false,
  dataSource: [],
  queryParams: {
    page: 1,
    pageSize: 10,
    total: 0,
    modelLabel: ''
  },
  payloadType: ['JSON', '二进制流'],
  modelCount: [],
  modelTemplateList: []
})

const formOptions = reactive({
  disabled: false,
  hideRequiredMark: false
})

const modalTitle = computed(() => state.opraState === 'add' ? '新增产品模型' : '编辑产品模型')

const useForm = Form.useForm

const router = useRouter()

const modelRef = reactive({
  modelTemplateId: '',
  modelLabel: '',
  transportType: null,
  payloadType: null,
  deviceType: '',
  modelDescription: '',
  rts: false
})

const rulesRef = reactive({
  modelLabel: [{ required: true, message: '请填写标题' }],
  transportType: [{ required: true, message: '请选择协议' }],
  payloadType: [{ required: true, message: '请填写数据格式' }]
})

watch(
  () => modelRef.modelTemplateId,
  () => {
    if (modelRef.modelTemplateId) {
      formOptions.hideRequiredMark = true
      formOptions.disabled = true
    } else {
      formOptions.hideRequiredMark = false
      formOptions.disabled = false
    }
  }
)

const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef)

const goDevicePage = (id: string) => {
  router.push({ path: '/device/index', query: { modelId: id } })
}

// 获取产品模型库列表
const getModelTemplateList = async () => {
  const { data } = await ModelController.modelTemplate({
    page: 1,
    pageSize: 200
  })
  state.modelTemplateList = data
}

// 获取统计
const getModelCount = async () => {
  const { data } = await ModelController.count()
  state.modelCount = Object.keys(data).map(key => {
    const item = ModelController.forwardStatisticMap.get(key)
    return {
      ...item,
      value: data[key]
    }
  })
}

const change = ({ current }) => {
  state.queryParams.page = current
  getModel()
  console.log('page:', current)
}

const ok = async () => {
  if (modelRef.modelTemplateId) {
    await opraModel()
    state.visible = false
    resetFields({})
    getModel()
  } else {
    validate().then(async () => {
      await opraModel()
      state.visible = false
      getModel()
      resetFields({})
    }).catch(() => {})
  }
}

const goDetailPage = (id: string) => {
  router.push({ path: '/product/detail', query: { id, type: 'model' } })
}

const confirmDel = async (id: string) => {
  await ModelController.del(id)
  getModel()
}

const openModel = (opraState: 'add' | 'update') => {
  state.opraState = opraState
  state.visible = true
}

const opraModel = async () => {
  if (state.opraState === 'add') {
    await ModelController.post(modelRef)
  }
}

const closeModel = () => {
  resetFields({})
  state.visible = false
}

const getModel = async () => {
  state.loading = true
  const { data, sum } = await ModelController.page(state.queryParams)
  state.loading = false
  state.dataSource = data
  state.queryParams.total = sum
}

onMounted(async () => {
  getModel()
  state.transport = await CommonController.getTransport()
  getModelCount()
  getModelTemplateList()
})
</script>

<style></style>
