<template>
  <div class='p-2'>

    <el-row :gutter='10' class='mb8'>
      <el-col :span='1.5'>
        <el-button type='primary' plain icon='Plus' @click='handleAdd'
                   v-hasPermi="['dms:deviceModeFunction:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span='1.5'>
        <el-button type='warning' plain icon='Back' @click='returnClose()'>返回</el-button>
      </el-col>
    </el-row>
    <el-table v-loading='loading' :data='deviceModeFunctionList' @selection-change='handleSelectionChange'>
      <!--            <el-table-column type='selection' width='55' align='center' />-->
      <el-table-column label='序号' type='index' width='50' align='center' v-if='columns[21].visible' />
      <el-table-column label='设备模型功能ID' align='center' prop='modeFunctionId' v-if='columns[0].visible' />
      <el-table-column label='设备模型' align='center' prop='deviceModeId'
                       v-if='columns[1].visible' />
      <el-table-column label='功能模式' align='center' prop='functionMode' v-if='columns[2].visible'>
        <template #default='scope'>
          <dict-tag :options='dms_function_mode' :value='scope.row.functionMode' />
        </template>
      </el-table-column>
      <el-table-column label='功能类型' align='center' prop='functionType'
                       v-if='columns[6].visible'>
        <template #default='scope'>
          <dict-tag :options='dms_function_type' :value='scope.row.functionType' />
        </template>
      </el-table-column>
      <el-table-column label='坐标标识' align='center' prop='coordinate' v-if='columns[3].visible'>
        <template #default='scope'>
          <dict-tag :options='dms_coordinate' :value='scope.row.coordinate' />
        </template>
      </el-table-column>
      <el-table-column label='功能名称' align='center' prop='functionName' v-if='columns[4].visible' />
      <el-table-column label='标识符' align='center' prop='functionIdentifier' v-if='columns[5].visible' />

      <el-table-column label='数据类型' align='center' prop='dataType' v-if='columns[7].visible'>
        <template #default='scope'>
          <dict-tag :options='dms_data_type' :value='scope.row.dataType' />
        </template>
      </el-table-column>
      <el-table-column label='数据定义' align='center' prop='dataDefinition' v-if='columns[8].visible' />
      <el-table-column label='运算性变量公式' align='center' prop='functionFormula' v-if='columns[9].visible' />
      <el-table-column label='单位' align='center' prop='propertyUnit' v-if='columns[10].visible' />
      <el-table-column label='显示标识' align='center' prop='displayFlag' v-if='columns[11].visible'>
        <template #default='scope'>
          <dict-tag :options='dms_display_flag' :value='scope.row.displayFlag' />
        </template>
      </el-table-column>
      <el-table-column label='读写标识' align='center' prop='rwFlag' v-if='columns[12].visible'>
        <template #default='scope'>
          <dict-tag :options='dms_rw_flag' :value='scope.row.rwFlag' />
        </template>
      </el-table-column>
      <el-table-column label='调用方式' align='center' prop='invokeMethod' v-if='columns[13].visible'>
        <template #default='scope'>
          <dict-tag :options='dms_invoke_method' :value='scope.row.invokeMethod' />
        </template>
      </el-table-column>
      <el-table-column label='事件类型' align='center' prop='eventType' v-if='columns[14].visible'>
        <template #default='scope'>
          <dict-tag :options='dms_event_type' :value='scope.row.eventType' />
        </template>
      </el-table-column>
      <el-table-column label='描述' align='center' prop='remark' v-if='columns[15].visible' />
      <el-table-column label='获取公式' align='center' prop='acquisitionFormula' v-if='columns[16].visible' />
      <el-table-column label='预留字段，顺序' align='center' prop='orderFlag' v-if='columns[17].visible' />
      <el-table-column label='预留字段，寄存器' align='center' prop='deviceRegister' v-if='columns[18].visible' />
      <el-table-column label='预留字段，步长' align='center' prop='propertyStep' v-if='columns[19].visible' />
      <el-table-column label='预留字段' align='center' prop='propertyField' v-if='columns[20].visible' />
      <el-table-column label='操作' align='center' class-name='small-padding fixed-width'>
        <template #default='scope'>
          <el-tooltip content='修改' placement='top'>
            <el-button link type='primary' icon='Edit' @click='handleUpdate(scope.row)'
                       v-hasPermi="['dms:deviceModeFunction:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content='删除' placement='top'>
            <el-button link type='primary' icon='Delete' @click='handleDelete(scope.row)'
                       v-hasPermi="['dms:deviceModeFunction:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show='total > 0' :total='total' v-model:page='queryParams.pageNum'
                v-model:limit='queryParams.pageSize' @pagination='getList' />

    <!-- 添加或修改设备模型功能对话框 -->
    <el-dialog :title='dialog.title' v-model='dialog.visible' width='600px' append-to-body>
      <el-form ref='deviceModeFunctionFormRef' :model='form' :rules='rules' label-width='120px'>
        <el-form-item label='设备模型名称' prop='deviceModeName'>
          <span>{{ topForm.deviceModeName }}</span>
        </el-form-item>
        <el-form-item label='功能类型' prop='functionType'>
          <el-radio-group v-model='form.functionType'>
            <el-radio
              v-for='dict in dms_function_type'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        <el-form-item label='功能模式' prop='functionMode'>-->
        <!--          <el-radio-group v-model='form.functionMode'>-->
        <!--            <el-radio-->
        <!--              v-for='dict in dms_function_mode'-->
        <!--              :key='dict.value'-->
        <!--              :value='dict.value'-->
        <!--            >{{ dict.label }}-->
        <!--            </el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label='坐标标识' prop='coordinate'>-->
        <!--          <el-radio-group v-model='form.coordinate'>-->
        <!--            <el-radio-->
        <!--              v-for='dict in dms_coordinate'-->
        <!--              :key='dict.value'-->
        <!--              :value='dict.value'-->
        <!--            >{{ dict.label }}-->
        <!--            </el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <el-form-item label='功能名称' prop='functionName'>
          <el-input v-model='form.functionName' placeholder='请输入功能名称' />
        </el-form-item>
        <el-form-item label='标识符' prop='functionIdentifier'>
          <el-input v-model='form.functionIdentifier' placeholder='请输入标识符' />
        </el-form-item>
        <el-form-item label='数据类型' prop='dataType'>
          <el-select v-model='form.dataType' placeholder='请选择数据类型'>
            <el-option
              v-for='dict in dms_data_type'
              :key='dict.value'
              :label='dict.label'
              :value='parseInt(dict.value)'
            ></el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label='数据定义' prop='dataDefinition'>-->
        <!--          <el-input v-model='form.dataDefinition' placeholder='请输入数据定义' />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label='运算性变量公式' prop='functionFormula'>-->
        <!--          <el-input v-model='form.functionFormula' placeholder='请输入运算性变量公式' />-->
        <!--        </el-form-item>-->
        <el-form-item label='单位' prop='propertyUnit'>
          <el-input v-model='form.propertyUnit' placeholder='请输入单位' />
        </el-form-item>
        <el-form-item label='显示标识' prop='displayFlag'>
          <el-radio-group v-model='form.displayFlag'>
            <el-radio
              v-for='dict in dms_display_flag'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='读写标识' prop='rwFlag'>
          <el-radio-group v-model='form.rwFlag'>
            <el-radio
              v-for='dict in dms_rw_flag'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        <el-form-item label='调用方式' prop='invokeMethod'>-->
        <!--          <el-radio-group v-model='form.invokeMethod'>-->
        <!--            <el-radio-->
        <!--              v-for='dict in dms_invoke_method'-->
        <!--              :key='dict.value'-->
        <!--              :value='dict.value'-->
        <!--            >{{ dict.label }}-->
        <!--            </el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label='事件类型' prop='eventType'>-->
        <!--          <el-radio-group v-model='form.eventType'>-->
        <!--            <el-radio-->
        <!--              v-for='dict in dms_event_type'-->
        <!--              :key='dict.value'-->
        <!--              :value='dict.value'-->
        <!--            >{{ dict.label }}-->
        <!--            </el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <el-form-item label='描述' prop='remark'>
          <el-input v-model='form.remark' type='textarea' placeholder='请输入描述' />
        </el-form-item>
        <!--        <el-form-item label='获取公式' prop='acquisitionFormula'>-->
        <!--          <el-input v-model='form.acquisitionFormula' placeholder='请输入获取公式' />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label='预留字段，顺序' prop='orderFlag'>-->
        <!--          <el-input v-model='form.orderFlag' placeholder='请输入预留字段，顺序' />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label='预留字段，寄存器' prop='deviceRegister'>-->
        <!--          <el-input v-model='form.deviceRegister' placeholder='请输入预留字段，寄存器' />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label='预留字段，步长' prop='propertyStep'>-->
        <!--          <el-input v-model='form.propertyStep' placeholder='请输入预留字段，步长' />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label='预留字段' prop='propertyField'>-->
        <!--          <el-input v-model='form.propertyField' placeholder='请输入预留字段' />-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class='dialog-footer'>
          <el-button :loading='buttonLoading' type='primary' @click='submitForm'>确 定</el-button>
          <el-button @click='cancel'>取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name='DeviceModeFunction' lang='ts'>
import {
  listDeviceModeFunction,
  getDeviceModeFunction,
  delDeviceModeFunction,
  addDeviceModeFunction,
  updateDeviceModeFunction
} from '@/api/dms/deviceModeFunction';
import {
  DeviceModeFunctionVO,
  DeviceModeFunctionQuery,
  DeviceModeFunctionForm
} from '@/api/dms/deviceModeFunction/types';
import { getDeviceMode, getDmsDeviceModeList } from '@/api/dms/deviceMode';
import { RouteLocationNormalized } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  dms_data_type,
  dms_display_flag,
  dms_invoke_method,
  dms_rw_flag,
  dms_event_type,
  dms_coordinate,
  dms_function_type,
  dms_function_mode
} = toRefs<any>(proxy?.useDict('dms_data_type', 'dms_display_flag', 'dms_invoke_method', 'dms_rw_flag', 'dms_event_type', 'dms_coordinate', 'dms_function_type', 'dms_function_mode'));

const deviceModeFunctionList = ref<DeviceModeFunctionVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const deviceModeFunctionFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const activeName = ref('1');//功能模式（1、属性，2、服务，3、事件）
const deviceModeId = ref(Number());
const topForm = ref({
  deviceModeName: undefined,
  remark: undefined,
  deviceModePic: undefined
});


/** 查询设备模型下拉树结构 */
const deviceModeList = ref([]);
const getDmsDeviceModeListSelect = async () => {
  let res = await getDmsDeviceModeList(null);
  deviceModeList.value = res.data;
};

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `设备模型功能ID`, visible: false },
  { key: 1, label: `设备模型`, visible: false },
  { key: 2, label: `功能模式`, visible: false },
  { key: 3, label: `坐标标识`, visible: false },
  { key: 4, label: `功能名称`, visible: true },
  { key: 5, label: `标识符`, visible: true },
  { key: 6, label: `功能类型`, visible: true },
  { key: 7, label: `数据类型`, visible: true },
  { key: 8, label: `数据定义`, visible: false },
  { key: 9, label: `运算性变量公式`, visible: false },
  { key: 10, label: `单位`, visible: true },
  { key: 11, label: `显示标识`, visible: true },
  { key: 12, label: `读写标识`, visible: true },
  { key: 13, label: `调用方式`, visible: false },
  { key: 14, label: `事件类型`, visible: false },
  { key: 15, label: `描述`, visible: true },
  { key: 16, label: `获取公式`, visible: false },
  { key: 17, label: `预留字段，顺序`, visible: false },
  { key: 18, label: `预留字段，寄存器`, visible: false },
  { key: 19, label: `预留字段，步长`, visible: false },
  { key: 20, label: `预留字段`, visible: false },
  { key: 21, label: `序号`, visible: true }
]);

const initFormData: DeviceModeFunctionForm = {
  modeFunctionId: undefined,
  deviceModeId: undefined,
  functionMode: undefined,
  coordinate: undefined,
  functionName: undefined,
  functionIdentifier: undefined,
  functionType: undefined,
  dataType: undefined,
  dataDefinition: undefined,
  functionFormula: undefined,
  propertyUnit: undefined,
  displayFlag: undefined,
  rwFlag: undefined,
  invokeMethod: undefined,
  eventType: undefined,
  remark: undefined,
  acquisitionFormula: undefined,
  orderFlag: undefined,
  deviceRegister: undefined,
  propertyStep: undefined,
  propertyField: undefined
};
const data = reactive<PageData<DeviceModeFunctionForm, DeviceModeFunctionQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    modeFunctionId: undefined,
    deviceModeId: undefined,
    functionMode: undefined,
    coordinate: undefined,
    functionName: undefined,
    functionIdentifier: undefined,
    functionType: undefined,
    dataType: undefined,
    dataDefinition: undefined,
    functionFormula: undefined,
    propertyUnit: undefined,
    displayFlag: undefined,
    rwFlag: undefined,
    invokeMethod: undefined,
    eventType: undefined,
    acquisitionFormula: undefined,
    orderFlag: undefined,
    deviceRegister: undefined,
    propertyStep: undefined,
    propertyField: undefined,
    params: {}
  },
  rules: {
    deviceModeId: [
      { required: true, message: '设备模型不能为空', trigger: 'blur' }
    ],
    functionMode: [
      { required: true, message: '功能模式不能为空', trigger: 'change' }
    ],
    functionIdentifier: [
      { required: true, message: '标识符不能为空', trigger: 'change' }
    ],
    functionName: [
      { required: true, message: '功能名称不能为空', trigger: 'blur' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备模型功能列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.deviceModeId = deviceModeId.value;
  queryParams.value.functionMode = activeName.value;
  const res = await listDeviceModeFunction(queryParams.value);
  deviceModeFunctionList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deviceModeFunctionFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceModeFunctionVO[]) => {
  ids.value = selection.map(item => item.modeFunctionId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  form.value.deviceModeId = deviceModeId.value;
  form.value.functionMode = '1';//功能模式（1、属性，2、服务，3、事件）
  form.value.functionType = '1';//功能类型(1、直采变量 2、手录变量 3、运算性变量)
  form.value.displayFlag = '1';//显示标识（0、不显示，1、显示，2、可累积显示）
  form.value.rwFlag = '2';//读写标识（1、读写，2、只读）
  dialog.title = '添加设备模型属性功能';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceModeFunctionVO) => {
  reset();
  const _modeFunctionId = row?.modeFunctionId || ids.value[0];
  const res = await getDeviceModeFunction(_modeFunctionId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改设备模型属性功能';
};

/** 提交按钮 */
const submitForm = () => {
  deviceModeFunctionFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.modeFunctionId) {
        await updateDeviceModeFunction(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addDeviceModeFunction(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DeviceModeFunctionVO) => {
  const _modeFunctionIds = row?.modeFunctionId || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备模型功能编号为"' + _modeFunctionIds + '"的数据项？').finally(() => loading.value = false);
  await delDeviceModeFunction(_modeFunctionIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 关闭按钮 */
const returnClose = () => {
  const obj: RouteLocationNormalized = {
    path: '/dms/deviceMode',
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined
  };
  proxy?.$tab.closeOpenPage(obj);
};

/** 查询设备模型数据 */
const getDeviceModeData = async () => {
  const router = useRouter();
  deviceModeId.value = router.currentRoute._rawValue.query && router.currentRoute._rawValue.query.deviceModeId;
  const res = await getDeviceMode(deviceModeId.value);
  Object.assign(topForm.value, {
    deviceModeName: res.data.deviceModeName,
    remark: res.data.remark,
    deviceModePic: res.data.deviceModePic
  });
};

onMounted(() => {
  getDeviceModeData();
  getDmsDeviceModeListSelect();
  getList();
});
</script>
