<!-- 算子程序管理 -->
<template>
  <div class="app-container model-detail">
    <!-- 新增/编辑表单 -->
    <el-card v-loading="loading">
      <template #header
        ><svg-icon icon-class="pause" style="width: 20px; height: 20px" />
        算子程序基本信息
      </template>
      <el-row>
        <el-col :lg="12" :xs="24">
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="算子类型" prop="oper_main_type">
              <el-select
                v-model="formData.oper_main_type"
                placeholder="请选择算子主类型"
                style="width: 100%"
                @change="handleChange"
              >
                <el-option
                  v-for="item in listOpt.operTypeList"
                  :key="item.oper_main_type"
                  :label="item.oper_main_type_name"
                  :value="item.oper_main_type"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="算子名称" prop="operator_id">
              <el-select
                v-model="formData.operator_id"
                placeholder="请选择算子名称"
                style="width: 100%"
                @change="handleChangeOperator"
              >
                <el-option
                  v-for="item in listOpt.operatorList"
                  :key="item.operator_id"
                  :label="item.operator_name"
                  :value="item.operator_id"
                >
                  <span style="float: left">{{ item.operator_name }}</span>
                  <span
                    style="
                      float: right;
                      color: var(--el-text-color-secondary);
                      font-size: 13px;
                    "
                  >
                    {{ item.oper_sub_type_name }}
                  </span>
                </el-option>
              </el-select>
              <!-- <el-select
                v-model="formData.operator_id"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请搜索选择算子名称"
                remote-show-suffix
                :remote-method="remoteMethod"
                :loading="selLoading"
                style="width: 100%"
                @change="handleChangeOperator"
              >
                <el-option
                  v-for="item in listOpt.operatorList"
                  :key="item.operator_id"
                  :label="item.operator_name"
                  :value="item.operator_id"
                >
                  <span style="float: left">{{ item.operator_name }}</span>
                  <span
                    style="
                      float: right;
                      color: var(--el-text-color-secondary);
                      font-size: 13px;
                    "
                  >
                    {{ item.oper_sub_type_name }}
                  </span>
                </el-option>
              </el-select> -->
            </el-form-item>
            <el-form-item label="适配硬件" prop="cmpt_hardware_type">
              <el-select
                v-model="formData.cmpt_hardware_type"
                placeholder="请选择适配硬件类型"
                style="width: 100%"
                @change="handleChangeCmpt"
              >
                <el-option
                  v-for="item in listOpt.cmptHardwareTypeList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="程序版本" prop="program_version">
              <el-input
                v-model="formData.program_version"
                type="number"
                placeholder="请输入程序版本"
              />
            </el-form-item>
            <el-form-item label="程序文件" prop="program_file_name">
              <el-upload
                v-model:file-list="fileList"
                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                ref="uploadRef"
                class="upload-demo"
                :on-exceed="handleFileExceed"
                :auto-upload="false"
                :limit="1"
                accept="application/x-tar"
              >
                <el-button type="primary"
                  ><el-icon class="el-icon--upload"> <i-ep-upload-filled /> </el-icon
                  >选择文件</el-button
                >
                <template #tip>
                  <div class="el-upload__tip">
                    请上传大小不超过 <strong style="color: red">10M</strong>，格式为
                    <strong style="color: red">gz</strong> 的文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :lg="12" :xs="24">
          <div style="padding-left: 35px" v-if="fileStatus">
            <el-form label-width="100px" size="small">
              <el-divider content-position="left"
                ><strong style="color: #409eff">算子文件预览</strong></el-divider
              >
              <el-input v-model="codeJson" :disabled="true" type="textarea" :rows="20" />
            </el-form>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="card-footer">
      <el-button type="primary" @click="handleSubmit"><i-ep-check />确 定</el-button>
      <el-button @click="closeBack"><i-ep-close />取 消</el-button>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import ConstApi from "@/api/const";
import { useUserStore } from "@/store";
import OperatorApi from "@/api/operator";

const router = useRouter();
const formRef = ref(ElForm); // 表单
const loading = ref(false); //  加载状态
const selLoading = ref(false); //  加载状态
const fileStatus = ref(false); //  文件状态
const codeJson = ref(""); //  文件信息

// 上传组件
const uploadRef = ref<UploadInstance>();
// 表单数据
const formData = reactive({
  status: 1,
});
const userStore = useUserStore();

// 基础数据列表
let listOpt = reactive({
  operTypeList: [],
  operatorList: [],
  cmptHardwareTypeList: [],
});

// 校验规则
const rules = reactive({
  oper_main_type: [{ required: true, message: "算子类型不能为空", trigger: "blur" }],
  operator_id: [{ required: true, message: "算子名称不能为空", trigger: "blur" }],
  cmpt_hardware_type: [{ required: true, message: "适配硬件不能为空", trigger: "blur" }],
  program_version: [{ required: true, message: "程序版本不能为空", trigger: "blur" }],
  program_file_name: [{ required: true, message: "程序文件不能为空", trigger: "blur" }],
});

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  formRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      formData.user_id = userStore.user?.id;
      formData.create_time = new Date();
      OperatorApi.addPrograms(formData)
        .then((res) => {
          if (res.data.code == 0) {
            ElMessage.success("保存成功");
            closeBack();
          }
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}, 3000);

// 超出限制，清空文件列表
function handleFileExceed() {
  uploadRef.value.clearFiles();
  ElMessage.warning("已清空文件列表,请重新上传！");
}

/** 返回默认页面 */
function closeBack() {
  router.push({ path: "/operatorLibrary/calculateParam" });
}

/** 搜索算子 */
const remoteMethod = (query: string) => {
  if (query) {
    selLoading.value = true;
    setTimeout(() => {
      let param = {
        page_num: 1,
        page_size: 999,
        operator_name: query,
        oper_main_type: formData.oper_main_type,
      };
      OperatorApi.list(param)
        .then((res) => {
          operatorList = res.data.data.operator_list;
        })
        .finally(() => {
          selLoading.value = false;
        });
    }, 200);
  } else {
    operatorList = [];
  }
};

/** 算子主类型改变 */
function handleChange() {
  formRef.value.validateField("oper_main_type");
  let param = {
    page_num: 1,
    page_size: 999,
    oper_main_type: formData.oper_main_type,
  };
  OperatorApi.list(param).then((res) => {
    listOpt.operatorList = res.data.data.operator_list;
  });
}

/** 选择算子名称 */
function handleChangeOperator() {
  formRef.value.validateField("operator_id");
  OperatorApi.findOne(formData.operator_id).then((res) => {
    //JSON转换
    codeJson.value = JSON.stringify(res.data.data.parameters);
    if(codeJson.value=='{}'){
      fileStatus.value = false;
    }else{
      fileStatus.value = true;
    }
  });
}

/** 选择适配硬件 */
function handleChangeCmpt() {
  formRef.value.validateField("cmpt_hardware_type");
}

// 初始化选项列表
const initData = () => {
  ConstApi.operMainType().then((res) => {
    listOpt.operTypeList = res.data.data.oper_main_type_list || [];
  });
  ConstApi.cmptHardwareType().then((res) => {
    listOpt.cmptHardwareTypeList = res.data.data.cmpt_hardware_type_list || [];
  });
};

onMounted(() => {
  initData();
});
</script>
<style scoped lang="scss">
.model-detail {
  :deep(.el-card__header) {
    padding: 8px 4px;
    display: flex;
    align-items: center;
  }
}
.sp-file {
  color: #29d;
}
.tb-base-info {
  line-height: 30px;
}
:deep(.svg-icon) {
  margin-right: 8px;
}
.card-footer {
  position: fixed;
  width: calc(100% - 215px);
  bottom: 0px;
  :deep(.el-card__body) {
    padding: 10px;
    .el-pagination {
      justify-content: end;
    }
  }
}
</style>
