<template>
  <el-form :model="form" ref="formRef" label-width="120px" :rules="formRules">
    <div class="form-container">
      <el-row :gutter="20">
        <!-- 标准代码编号 -->
        <el-col :span="8">
          <el-form-item label="标准代码编号" prop="codeNum">
            <el-input v-model="form.codeNum" placeholder="请输入标准代码编号" />
          </el-form-item>
        </el-col>

        <!-- 标准代码名称 -->
        <el-col :span="8">
          <el-form-item label="标准代码名称" prop="codeName">
            <el-input v-model="form.codeName" placeholder="请输入标准代码名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <!-- 标准代码类型 -->
        <el-col :span="8">
          <el-form-item label="标准代码类型" prop="codeType">
            <el-select
              v-model="form.codeType"
              placeholder="请选择标准代码类型"
              maxlength="30"
              @change="changeCodeType"
            >
              <el-option
                v-for="dict in std_code_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 归属系统 -->
        <el-col :span="8" v-show="showSys">
          <el-form-item label="归属系统" prop="sysId">
            <el-select
              v-model="form.sysId"
              placeholder="请选择归属系统"
              maxlength="30"
              @change="dataChange"
            >
              <el-option
                v-for="dict in dbResourceOldList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 代码映射 -->
        <el-col :span="8" v-show="showSys">
          <el-form-item label="代码映射" prop="codeMapId">
            <el-select
              v-model="form.codeMapId"
              placeholder="请选择代码映射"
              maxlength="30"
              @change="mapChange"
            >
              <el-option
                v-for="dict in companyist"
                :key="dict.id"
                :label="dict.codeName"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </div>

    <!-- 查询表单 -->
    <!-- <div class="query-form-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="代码值/名称" prop="codeNum">
          <el-input
            v-model="queryParams.codeNum"
            placeholder="请输入标准代码编号"
            clearable
            style="width: 220px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div> -->
  </el-form>

  <!-- 操作按钮 -->
  <el-row :gutter="10" class="mb8">
    <el-col :span="1.5">
      <el-button
        type="primary"
        plain
        icon="Plus"
        @click="handleAdd"
        v-hasPermi="['meta:metaSecurityCol:add']"
      >新增</el-button>
    </el-col>

    <el-col :span="1.5">
      <el-button
        type="danger"
        plain
        icon="Delete"
        :disabled="multiple"
        @click="handleRemove"
        v-hasPermi="['meta:metaSecurityCol:remove']"
      >删除</el-button>
    </el-col>
  </el-row>

  <!-- 表格展示 -->
  <el-table
    v-loading="loading"
    :data="tableData"
    @selection-change="handleSelectionChange"
    @row-dblclick="handleRowDblClick"
    border
    style="width: 100%"
  >
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column
      label="代码值"
      align="center"
      prop="codeNum"
      :editable="true"
    >
      <template #default="scope">
        <el-input
          v-if="scope.row.isEditing"
          v-model="scope.row.codeNum"
          size="small"
          placeholder="请输入代码值"
          @blur="handleBlur(scope.row)"
        />
        <span v-else>{{ scope.row.codeNum }}</span>
      </template>
    </el-table-column>

    <el-table-column
      label="代码含义"
      align="center"
      prop="codeName"
      :editable="true"
    >
      <template #default="scope">
        <el-input
          v-if="scope.row.isEditing"
          v-model="scope.row.codeName"
          size="small"
          placeholder="请输入代码含义"
          @blur="handleBlur(scope.row)"
        />
        <span v-else>{{ scope.row.codeName }}</span>
      </template>
    </el-table-column>

    <el-table-column
      label="代码映射"
      align="center"
      prop="代码映射"

    >
      <template #default="scope">
        <el-link
          type="primary"
          :underline="true"
          @click="handleCodeClick(scope.row, scope.$index)"
          style="cursor: pointer"
        >
        <span v-if="!scope.row.codeMapName">代码映射</span>
        <span v-else>{{ scope.row.codeMapName }}</span>        
        </el-link>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog  title="代码映射" v-model="mapVisible" width="1000px">
      <!-- 引入第二个页面组件 -->
      <code-item-common  ref="showCodeDialog" v-if="mapVisible" :codeId="form.codeMapId"/>
      <template #footer>
        <el-button @click="handleCancel2">取消</el-button>
        <el-button type="primary" @click="handleSave2">确定</el-button>
      </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, toRefs } from 'vue';
import { listStdCode,listStdCodeCompany,addStdCode,updateStdCode } from "@/api/datastd/stdcode"; // 更新为新的接口
import codeItemCommon from './codeItemCommon.vue'; // 引入第二个页面组件

const { proxy } = getCurrentInstance();
const { std_code_status } = proxy.useDict("std_code_status");

const props = defineProps({
  rowData: {
    type: Object,
    required: false
  },
  dbResourceOldList: {
    type: Object,
    required: false
  }
});

const queryParams = ref({
  codeNum: '',
  parentId: props.rowData.id,
  codeName: '',
  codeType: '',
  sysName: '',
  classId: 'codeItem',
  sysId: '',
  pageNum: 1,
  pageSize: 100
});

const form = ref({
  id: "",
  codeNum: '',
  codeName: '',
  codeType: 'company',
  codeStatus: '',
  sysName: '',
  classId: 'code',
  codeMapId: '',
  codeMapName: '',
  codeMapNum: '',
  sysId: undefined
});
const handleCancel2 = () => {
  mapVisible.value = false;
};

const tableData = ref([]);
const companyist = ref([]);
const loading = ref(false);
const showSys = ref(false);
const mapVisible = ref(false);
const multiple = ref(false);
function dataChange(data) {
  // 从 dbResourceOldList 中查找对应的 name
  const selectedItem = props.dbResourceOldList.find(item => item.id === data);
  if (selectedItem) {
    // 如果找到对应的项，将 name 赋值给 form.value.dbRName
    form.value.sysName = selectedItem.name;
  } else {
    // 如果未找到，清空 form.value.dbRName
    form.value.sysName = '';
  }
}

function mapChange(data) {
  const selectedItem = companyist.value.find(item => item.id === data);
  console.log("selectmap",selectedItem,data)
  if (selectedItem) {
    // 如果找到对应的项，将 name 赋值给 form.value.dbRName
    form.value.codeMapName = selectedItem.codeName;
    form.value.codeMapNum = selectedItem.codeNum;
  } else {
    // 如果未找到，清空 form.value.codeMapName
    form.value.codeMapName = '';
  }
}
//初始话判断展示系统及映射下拉选
if (props.rowData.id) {
  form.value = { ...props.rowData };
  if (form.value.codeType == "sys") {
    showSys.value = true;
  } else {
    showSys.value = false;
  }
}

// 双击行进入编辑模式
const handleRowDblClick = (row) => {
  row.isEditing = true;
};
const selectedRow = ref(null); // 传递给 codeItem 组件的数据
const selectedRowIndex = ref(null); // 传递给 codeItem 组件的数据

// 失去焦点时保存编辑结果
const handleBlur = (row) => {
  row.isEditing = false;
  // 可以在这里发送请求保存编辑的结果
  console.log('保存编辑', row);
};

// 获取数据列表
const getList = async () => {
  loading.value = true;
  console.log(queryParams.value,"queryParams.value")
  const response = await listStdCode(queryParams.value);
  tableData.value = response.rows.map(item => ({ ...item, isEditing: false }));
  loading.value = false;
};

const getcompanyList = async () => {
  const response = await listStdCodeCompany();
  companyist.value = response.rows;
  console.log(companyist.value,"companyCodeList")
};
const formRules = reactive({
  codeNum: [{ required: true, message: "请输入标准代码编号", trigger: "blur" }],
  codeName: [{ required: true, message: "请输入标准代码名称", trigger: "blur" }]
});
const handleCodeClick = (row,index) => {
  selectedRow.value=row
  selectedRowIndex.value=index
  if(form.value.codeMapId){
    mapVisible.value=true
  }else {
    proxy.$modal.msgWarning("请选择关联代码！");

  }
  console.log(index,'点击了标准代码名称', row);
};
const handleSave2 =async () => {
  const child = proxy.$refs.showCodeDialog;
 console.log(child.selections,"父组件获取")
 const mapList=child.selections
 if(mapList.length!=1){
  proxy.$modal.msgWarning("请选择一条代码进行映射");

 }else{
  const mapCodeItem=child.selections[0]
  if (selectedRow.value) {
        tableData.value[selectedRowIndex.value].codeMapId = mapCodeItem.id;
        tableData.value[selectedRowIndex.value].codeMapName = mapCodeItem.codeName;
        tableData.value[selectedRowIndex.value].codeMapNum = mapCodeItem.codeNum;

      tableData.value = [...tableData.value]; // This ensures reactivity is triggered

      mapVisible.value = false; 

      proxy.$modal.msgSuccess("码值映射成功");

 }}
};
const handleSave = async () => {
  // 检查是否有 ID，决定调用哪个接口
  const params = { code: form.value, code_item_list: tableData.value };

  try {
    let response;
    if (props.rowData.id) {
      // 如果 ID 存在，调用 updateStdCode
      response = await updateStdCode(params);
      if (response.success) {
        proxy.$modal.msgSuccess(response.msg);
      } else {
        proxy.$modal.msgError(response.msg);
      }
    } else {
      // 如果 ID 为空，调用 addStdCode
      response = await addStdCode(params);
      if (response.success) {
        proxy.$modal.msgSuccess(response.msg);
      } else {
        proxy.$modal.msgError(response.msg);
      }
    }

    // 根据 response.success 返回 true 或 false
    if (response.success) {
      // 操作成功
      return true;
    } else {
      // 操作失败
      return false;
    }

  } catch (error) {
    console.error('保存时出错:', error);
    // 这里可以弹出错误提示
    return false;  // 出现异常时返回 false
  }
};

const handleSelectionChange = (selection) => {
  multiple.value = selection.length > 0;
};



function changeCodeType(data) {
  if (data != "company") {
    showSys.value = true;
    form.value.sysName = "";
    form.value.sysId = undefined;
  } else {
    showSys.value = false;
    form.value.sysName = "公司级";
    form.value.sysId = 10000;
  }
}
// 新增行
const handleAdd = () => {
  const newRow = {id:'',classId: 'codeItem',parentId: props.rowData.id,codeNum: '', codeName: '',  codeMapId: '',
  codeMapName: '',
  codeMapNum: '', isEditing: true };
  tableData.value.push(newRow);
};

// 删除选中行
const handleRemove = () => {
  const selectedRows = tableData.value.filter(row => row.isSelected);
  tableData.value = tableData.value.filter(row => !row.isSelected);
};
defineExpose({
  handleSave
});
onMounted(() => {
  getList();
  getcompanyList()
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.form-container {
  margin-bottom: 20px;
}

.query-form-container {
  margin-bottom: 20px;
}

.el-table .el-input {
  width: 100%;
}
</style>
