<template>
  <StatisticsTemplate
      title="规则统计"
      :list="state.TaskCount"
  />

<a-card style="margin-top: 20px;" >
  <a-row justify="space-between" >
    <a-col span="12" >
        <a-row :gutter="[8, 8]" >
          <a-col><a-input allowClear placeholder="请输入任务名称" v-model:value="queryParamsState.taskLabel"/></a-col>
          <a-col>
            <a-select
              allowClear
              style="width: 170px"
              v-model:value="queryParamsState.status"
              placeholder="请选择任务状态"
            >
              <a-select-option
                v-for="item in statusList"
                :key="item.key"
                :value="item.key"
              >
                {{item.label}}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col>
            <a-button type="primary" @click="getTaskPage">搜索</a-button>
          </a-col>
        </a-row>

    </a-col>
    <a-col span="12" >
      <a-row justify="end" >
        <a-col>
          <a-space>
            <a-button type="primary" @click="openModal('add')" >新增任务</a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-col>
  </a-row>

  <a-table
    style="margin-top: 20px;"
    :columns="columns"
    :data-source="state.dataSource"
    :loading="state.loading"
    :pagination="queryParamsState"
    @change="changePage"
  >
    <template #bodyCell="{column, record}">
      <template v-if="column.key === 'id'" >
        <a @click="openModal('update', record.id)" >{{record.id}}</a>
        </template>
          <template v-if="column.key === 'status'" >
            <a-switch
              @click="changeStatus(record)"
              v-model:checked="record.status"
              checked-children="运行中"
              un-checked-children="已关闭"
            />
          </template>
          <template v-if="column.key === 'action'" >
            <a-space>
              <a @click="openModal('update', record.id)" >编辑</a>
              <a-popconfirm
                  title="确实要删除吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="delTask(record.id)"
                >
                <a>删除</a>
                </a-popconfirm>
            </a-space>
          </template>
    </template>
  </a-table>

  <modal-pro
    style="width: 1000px"
    :label="modalTitle"
    :open="state.visible"
    destroyOnClose
    @cancel="state.visible = false"
    @ok="ok"
  >
    <a-form :label-col="{span: 4}" :wrapper-col="{span: 16}">
      <a-form-item label="任务名称" v-bind="validateInfos.taskLabel">
        <a-input allowClear v-model:value="modalRef.taskLabel"  />
      </a-form-item>
      <a-form-item label="任务描述"  v-bind="validateInfos.taskDescription">
        <a-input allowClear v-model:value="modalRef.taskDescription" />
      </a-form-item>
      <a-form-item label="cron表达式" v-bind="validateInfos.cornDescr">
        <cron-ant
          locale="zh"
          v-model="modalRef.cornDescr"
          :button-props="{ type: 'primary', shape: 'round'}"
        />
      </a-form-item>
      <a-form-item label="选择产品"  v-bind="validateInfos.modelId">
        <a-select
        allowClear
          placeholder="请选择产品"
          v-model:value="modalRef.taskConfig.modelId"
        >
          <a-select-option
            v-for="model in state.modelList"
            :key="model.id"
            :value="model.id"
          >
            {{model.modelLabel}}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="选择设备" v-bind="validateInfos.deviceId">
        <a-select
        allowClear
          placeholder="请选择产品"
          v-model:value="modalRef.taskConfig.deviceId"
        >
          <a-select-option
            v-for="device in state.deviceList"
            :key="device.id"
            :value="device.id"
          >
            {{device.deviceLabel}}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="任务类型" v-bind="validateInfos.taskType">
        <a-select allowClear v-model:value="modalRef.taskConfig.taskType" >
          <a-select-option
            :value="item"
            v-for="item in TaskController.taskTypeList"
            :key="item"
          >
            {{TaskController.taskTypeMap.get(item)?.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <span v-if="modalRef.taskConfig.taskType === 'DEVICE_CMD'" >
        <a-form-item label="选择命令" >
          <a-select
          allowClear
            style="width: 170px;"
            v-model:value="modalRef.taskConfig.cmdId"
          >
            <a-select-option
              v-for="cmdItem in state.cmdList"
              :key="cmdItem.id"
              :value="cmdItem.id"
            >
            {{cmdItem.cmdLabel}}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="命令参数" >
          <div
            v-for="(item, index) in modalRef.taskConfig.cmdParameters"
            :key="index"
            style="margin-bottom: 10px;"
          >
            <a-input-group compact  >
              <a-input allowClear placeholder="key"  disabled v-model:value="item.paramLabel" style="width: 50%" />
              <a-input allowClear placeholder="value" v-model:value="item.dataUnit" style="width: 50%" />
            </a-input-group>
          </div>
        </a-form-item>
      </span>
      <span v-if="modalRef.taskConfig.taskType === 'DEVICE_MSG'" >
        <a-form-item label="主题" >
          <a-input allowClear  v-model:value="modalRef.taskConfig.topic"  />
        </a-form-item>
        <a-form-item label="消息名称" >
          <a-input allowClear v-model:value="modalRef.taskConfig.msgLabel"  />
        </a-form-item>
        <a-form-item label="消息内容" >
          <a-textarea :auto-size="{ minRows: 2, maxRows: 5 }" v-model:value="modalRef.taskConfig.msgPayload"  />
        </a-form-item>
      </span>

      <!-- @error="error=$event" -->
    </a-form>
  </modal-pro>
</a-card>

<modal-pro
    style="width: 700px;overflow: hidden;"
    label="选择设备"
    :open="state.deviceModalVisible"
    @cancel="state.deviceModalVisible = false"
    @ok="selectDevice"
  >
    <SelectDevice
      ref="selectDeviceRef"
    />
</modal-pro>

</template>
<script lang='ts' setup >
import { TaskController } from '@/controller/iot/task'
import { computed, onMounted, reactive, ref, toRefs, watch } from 'vue'
import { Form } from 'ant-design-vue'
import { DeviceContriller, ModelAttrController, ModelCmdController, ModelController } from '@/controller'
import SelectDevice from '@/pages/iot/rule/components/selectDevice.vue'
import StatisticsTemplate from '@/components/StatisticsTemplate/index.vue'

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    key: 'id'
  },
  {
    title: '任务名称',
    dataIndex: 'taskLabel',
    key: 'taskLabel'
  },
  {
    title: '任务描述',
    dataIndex: 'taskDescription',
    key: 'taskDescription'
  },
  {
    title: 'corn',
    dataIndex: 'cornDescr',
    key: 'cornDescr'
  },
  {
    title: '任务状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action'
  }
]

const useForm = Form.useForm

const statusList = [
  { key: true, label: '开启' },
  { key: false, label: '关闭' }
]

const queryParamsState = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
  taskLabel: '',
  status: null
})

const modalTitle = computed(() => state.opraState === 'add' ? '新增任务' : '编辑任务')

const state = reactive({
  dataSource: [],
  loading: false,
  opraState: 'add',
  visible: false,
  modelList: [],
  cmdList: [],
  attrList: [],
  deviceList: [],
  deviceModalVisible: false,
  taskId: '',
  TaskCount: []
})

const modalRef = reactive({
  taskLabel: '',
  taskDescription: '',
  cornDescr: '',
  taskConfig: {
    taskType: '',
    deviceId: '',
    deviceLabel: '',
    modelId: '',
    cmdLabel: '',
    cmdParameters: [],
    cmdId: '',
    msgLabel: '',
    msgPayload: '',
    topic: ''
  }
})

const selectDeviceRef = ref('')

watch(
  () => modalRef.taskConfig.modelId,
  () => {
    getCmdList()
    getAttrList()
  }
)

watch(
  () => modalRef.taskConfig.cmdId,
  () => {
    if (modalRef.taskConfig.taskType === 'DEVICE_CMD') {
      const cmdDetail = state.cmdList.find(item => item.id === modalRef.taskConfig.cmdId)!
      console.log('cmdDetail:', state.cmdList, cmdDetail)

      if (cmdDetail && cmdDetail.cmdParams) {
        modalRef.taskConfig.cmdParameters = cmdDetail.cmdParams

        modalRef.taskConfig.cmdLabel = cmdDetail.cmdLabel
      }
    }
  }
)

const { resetFields, validate, validateInfos } = useForm(modalRef, reactive({
  taskLabel: [{ required: true, message: '请填写任务名称' }],
  taskDescription: [{ required: true, message: '请填写任务描述' }],
  cornDescr: [{ required: true, message: '请填写corn表达式' }],
  taskType: [{ required: true, message: '请选择任务类型' }],
  modelId: [{ required: true, message: '请选择产品' }],
  deviceId: [{ required: true, message: '请选择设备' }]
}))

const changeStatus = async (record) => TaskController.updateStatus(record.id, record.status)

// 选择设备
const selectDevice = () => {
  const _device = selectDeviceRef.value.getSelectDevice()
  modalRef.taskConfig.deviceId = _device.id
  modalRef.taskConfig.deviceLabel = _device.deviceLabel
  state.deviceModalVisible = false
}

const ok = () => {
  validate().then(async () => {
    const obj = {}
    if (modalRef.taskConfig.taskType === 'DEVICE_CMD') {
      modalRef.taskConfig.cmdParameters.forEach(item => {
        obj[item.paramLabel] = item.dataUnit
      })
      modalRef.taskConfig.cmdParameters = obj
    }
    console.log(modalRef)

    if (state.opraState === 'add') {
      await TaskController.add(modalRef)
    } else {
      await TaskController.update({ ...modalRef, id: state.taskId })
    }

    state.visible = false
    getTaskPage()
  })
}

const delTask = async (id: string) => {
  await TaskController.del(id)
  getTaskPage()
}

const openModal = (opraState: 'add' | 'update', id = '') => {
  resetFields()
  state.opraState = opraState
  state.visible = true
  state.taskId = id
  if (opraState === 'update') {
    getTaskById(id)
  }
}

const getCmdList = async () => {
  const { data } = await ModelCmdController.list({ modelId: modalRef.taskConfig.modelId })
  state.cmdList = data
}

// 获取属性
const getAttrList = async () => {
  const { data } = await ModelAttrController.list({ modelId: modalRef.taskConfig.modelId })
  state.attrList = data
}

const getModelList = async () => {
  const { data } = await ModelController.list()
  state.modelList = data
}

const getDeviceList = async () => {
  const { data } = await DeviceContriller.list()
  state.deviceList = data
}

const getStatistics = async () => {
  const { data } = await TaskController.statistics()
  state.TaskCount = Object.keys(data).map(key => {
    const item = TaskController.taskStatisticsMap.get(key)
    return {
      ...item,
      value: data[key]
    }
  })
  console.log('11', state.TaskCount)
}

const getTaskById = async (id: string) => {
  const { data } = await TaskController.byId(id)
  console.log('getTaskById:', data)

  if (data.taskConfig.taskType === 'DEVICE_CMD') {
    const cmdParameters = Object.keys(data.taskConfig.cmdParameters).map(key => {
      return { key, value: data.taskConfig.cmdParameters[key] }
    })
    data.taskConfig.cmdParameters = cmdParameters
  }

  resetFields(data)
}

const getTaskPage = async () => {
  state.loading = true
  const { data, sum } = await TaskController.page(queryParamsState)
  state.loading = false
  state.dataSource = data
  queryParamsState.total = sum
}

const changePage = ({ current }) => {
  queryParamsState.page = current
  getTaskPage()
}

onMounted(() => {
  getTaskPage()
  getModelList()
  getDeviceList()
  getStatistics()
})

</script>
<style lang='less' scoped >
</style>
