<template>
  <a-layout style="height: 100%; padding: 5px; padding-left: 0px; min-width: 300px">
    <a-layout-content style="padding: 5px; height: 100%; border: 1px solid #d1dbe5">
      <a-card class="box-card" style="padding: 0px;height: 100%;" :body-style='{ padding: "5px" }'>
        <lt-a-form contendPadding="5px" :fill="true" :fit="false" style="border-width: 0px; height: 100%"
          @updateData="handleUpdateForm" :initial-values="form">
          <a-form ref="refFormComFunct" layout="horizontal" :inline="false" id="refFormComFunct" :inline-message="true"
            label-width="100px" style="width: 100%;" :labelCol="{
              span: 6
            }" :rules="rules" :model="form">
            <a-row>
              <a-col :span="24">
                <a-form-item label="生产工艺" name="FunctionCode">
                  <a-select v-model:value="FunctionCode" allowClear
                    :disabled="Status == 1 || Status == 3 || Status == 5" :filterOption="filterOption"
                    :showSearch="true">
                    <a-select-option v-for="item in funOption" :key="item.FunctionCode" :value="item.FunctionCode"
                      :label="item.FunctionName">{{
                        item.FunctionName }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-item label="投料位置" name="RecipeStyleName">
                  <a-input v-model:value="RecipeStyleName" :readonly="true" :title="RecipeStyleName"></a-input>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row v-if="showMaterailRow && showMatreial">
              <a-row style="width: 100%;">
                <a-row style="width: 100%;">
                  <a-col :span="24">
                    <a-form-item :label="materialFiledName" :title="materialFiledName" name="EditMatName"
                      v-if="selectMatType == 'EditMatName'" style="white-space: nowrap; overflow: hidden"
                      :rules="DnyRules('EditMatName')">
                      <a-input v-model:value="form.EditMatName" :title="form.EditMatName"
                        :readonly="Status == 1 || Status == 3 || Status == 5" @focus="handleFoucus('EditMatName')"
                        @input="handleInput">
                      </a-input>
                    </a-form-item>
                    <a-form-item :label="materialFiledName" :title="materialFiledName" name="RecipeMatName"
                      v-if="selectMatType == 'RecipeMatName'" style="white-space: nowrap; overflow: hidden"
                      :rules="DnyRules('RecipeMatName')">
                      <a-input v-model:value="form.RecipeMatName" :title="form.RecipeMatName"
                        :readonly="Status == 1 || Status == 3 || Status == 5" @focus="handleFoucus('RecipeMatName')"
                        @input="handleInput" />
                    </a-form-item>
                    <a-form-item :label="materialFiledName" :title="materialFiledName" name="DisplayMaterialName"
                      v-if="selectMatType == 'DisplayMaterialName'" style="white-space: nowrap; overflow: hidden"
                      :rules="DnyRules('DisplayMaterialName')">
                      <a-input v-model:value="form.DisplayMaterialName" :title="form.DisplayMaterialName"
                        :readonly="Status == 1 || Status == 3 || Status == 5"
                        @focus="handleFoucus('DisplayMaterialName')" @input="handleInput" />
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row style="width: 100%;display: flex;" v-if="showMatreial == true">
                  <a-row style="height: 342px;width: 100%;padding: 2px;border: 1px solid #d1dbe5;margin-top: 2px;">
                    <erpBomList v-if="isMatFromERP == true" v-model:selectRowData="materialData" :matFilter="matFilter"
                      :ErpBomCols="ErpBomCols" :ErpBomDetails="ErpBomDetails" @row-dbclick="handleMatDbClick">
                    </erpBomList>
                    <materialList v-else v-model:selectRowData="materialData" :matFilter="matFilter" :matCol="matCol"
                      :MaterialCateOption="MaterialCateOption" @row-dbclick="handleMatDbClick"></materialList>
                  </a-row>
                  <a-row style="text-align: center;margin: auto;border: 1px solid #d1dbe5;width: 100%;margin-top: 2px;">
                    <div style="padding: 5px;width: 100%;">
                      <a-button type="primary" v-on:click="handleMatfirm">
                        <template #icon>
                          <check-outlined />
                        </template>
                        确认
                      </a-button>
                      <a-button v-on:click="handleMatClose" style="margin-left: 10px;">
                        <template #icon>
                          <close-outlined />
                        </template>
                        返回
                      </a-button>
                    </div>
                  </a-row>
                </a-row>
              </a-row>
            </a-row>
            <a-row v-else v-for="item in editFunParam" :key="item.OrderId" v-show="item.FieldName != 'EditFunName' &&
              item.FieldName != 'ExpressionItemId'" style="width: 100%;">
              <a-row v-if="item.FieldName == 'CylinderClass'" style="width: 100%;">
                <a-col :span="24">
                  <a-form-item label="容器类型" name="CylinderClass">
                    <a-select v-model:value="CylinderClass" allowClear
                      :disabled="Status == 1 || Status == 3 || Status == 5" :filterOption="filterOption"
                      :showSearch="true">
                      <a-select-option v-for="item in baseParameterOption" :key="item.value" :value="item.value"
                        :label="item.label">{{
                          item.label }}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row style="height: 370px;width: 100%;" v-else-if="item.FieldName == 'Script' && showMatreial == false">
                <codeMirror :hintWords="ScriptVar" v-model:scriptData="item.Script"></codeMirror>
              </a-row>
              <a-row v-else-if="item.ParamStyle == 1" style="width: 100%;">
                <a-col :title="item.ParamName" :span="24">
                  <a-form-item :label="item.ParamName" :name="item.FieldName" v-if="item.ParamStyle == 1"
                    style="white-space: nowrap; overflow: hidden" :rules="DnyRules(item.FieldName)">
                    <a-checkbox v-model:checked="form[item.FieldName]" v-if="item.ParamStyle == 1"
                      :disabled="Status == 1 || Status == 3 || Status == 5" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row v-else-if="showInput(item)" style="width: 100%;">
                <a-col :title="item.ParamName" :span="24">
                  <a-form-item :label="item.ParamName" :title="item.ParamName" :name="item.FieldName"
                    style="white-space: nowrap; overflow: hidden" :rules="DnyRules(item.FieldName)">
                    <a-input v-if="item.FieldName == 'Remark'" v-model:value="form[item.FieldName]"
                      :title="form[item.FieldName]" :max="item.MaxValue" :min="item.MixValue" type="textarea"
                      :readonly="_getReadOnlyItem(item.FieldName)" @focus="handleFoucus(item.FieldName)"
                      @input="handleInput" />
                    <a-input v-else-if="item.FieldName == 'Standant' ||
                      item.FieldName == 'SlowValue' ||
                      item.FieldName == 'ErrorLimit' ||
                      item.FieldName == 'RemarkValue' ||
                      item.FieldName == 'RemarkValue2' ||
                      item.FieldName == 'RealValue' ||
                      item.FieldName == 'LastRealValue'
                    " v-inputFloat v-model:value="form[item.FieldName]" :title="form[item.FieldName]"
                      :max="item.MaxValue" :min="item.MixValue" :readonly="_getReadOnlyItem(item.FieldName)"
                      @focus="handleFoucus(item.FieldName)" @input="handleInput">
                    </a-input>
                    <a-input v-else-if="item.FieldName == 'TargetVal' ||
                      item.FieldName == 'EditTargetVal' ||
                      item.FieldName == 'EidtFunTargetVal'" v-inputFloatNegative v-model:value="form[item.FieldName]"
                      :title="form[item.FieldName]" :max="item.MaxValue" :min="item.MixValue"
                      :readonly="_getReadOnlyItem(item.FieldName)" @focus="handleFoucus(item.FieldName)"
                      @input="handleInput">
                    </a-input>
                    <!-- 如果是材料名称只能选择，则生成带图标的input -->
                    <a-input v-else-if="isMustSelectMaterialName == true &&
                      (item.FieldName == 'EditMatName' ||
                        item.FieldName == 'RecipeMatName' ||
                        item.FieldName == 'DisplayMaterialName')" v-model:value="form[item.FieldName]"
                      :title="form[item.FieldName]" :readonly="_getReadOnlyItem(item.FieldName)"
                      @focus="handleFoucus(item.FieldName)" @input="handleInput">
                      <template #suffix>
                        <a-tooltip>
                          <search-outlined @click="handleFoucus(item.FieldName)" />
                        </a-tooltip>
                      </template>
                    </a-input>
                    <!-- 如果是材料名称只能选择，则生成带按钮的input -->
                    <a-input-search v-else-if="isMustSelectMaterialName == false &&
                      (item.FieldName == 'EditMatName' ||
                        item.FieldName == 'RecipeMatName' ||
                        item.FieldName == 'DisplayMaterialName')" v-model:value="form[item.FieldName]"
                      :title="form[item.FieldName]" :readonly="_getReadOnlyItem(item.FieldName)"
                      @search="handleFoucus(item.FieldName, 'select')" @input="handleInput">
                    </a-input-search>
                    <a-input v-else v-model:value="form[item.FieldName]" :title="form[item.FieldName]"
                      :max="item.MaxValue" :min="item.MixValue" :readonly="_getReadOnlyItem(item.FieldName)"
                      @focus="handleFoucus(item.FieldName)" @input="handleInput">
                    </a-input>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row v-else-if="showSelect(item)" style="width: 100%;">
                <a-col :title="item.ParamName" :span="24">
                  <a-form-item :label="item.ParamName" :title="item.ParamName" :name="item.FieldName"
                    style="white-space: nowrap; overflow: hidden" :rules="DnyRules(item.FieldName)">
                    <a-select v-model:value="form[item.FieldName]" @change="handleInputSelect(item)"
                      v-if="showCommonSelect(item)" style="width: 100%;" allowClear>
                      <a-select-option v-for="list in item.SelectItems" :key="list.ItemId" :label="list.ItemName"
                        :value="list.ItemId.toString()">{{ list.ItemName }}
                      </a-select-option>
                    </a-select>
                    <a-select v-model:value="form[item.FieldName]" @change="handleInput" v-else style="width: 100%;"
                      allowClear>
                      <a-select-option v-for="list in getSelectItems(item)" :key="list.ItemId" :label="list.ItemName"
                        :value="list.ItemId.toString()">
                        {{ list.ItemName }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-row>
            <a-row v-if="moduleType == 'Formular' && showExpressionOption == true">
              <a-col :span="24">
                <a-form-item label="计算公式" name="ExpressionItemId" :rules="DnyRules('ExpressionItemId')">
                  <a-select style="width: 100%" v-model:value="ExpressionItemId" allowClear
                    :disabled="Status == 1 || Status == 3 || Status == 5" @change="handleExpresChange">
                    <a-select-option v-for="item in ExpressionOption" :key="item.key" :value="item.key">{{
                      item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row v-if="funStyle == 25 || funStyle == 26" style="height: 410px">
              <a-row v-if="showExpression == false" style="width: 100%; height: 410px; margin: 0; padding: 0; ">
                <EXList style="height: 100%" ref="refexlist" v-if="showExpression == false" :data="FormularMCI"
                  :EXItemCols="innerEXICols" :funStyle="funStyle" :showTreeOperate="showTreeOperate"
                  :showOperate="Status == 1 || Status == 3 || Status == 5" @changeMCI="handleMciChnage"></EXList>
              </a-row>
              <a-row v-else style="width: 100%; height: 370px; margin: 0; padding: 0">
                <a-row style="height: 100%">
                  <materialList v-model:selectRowData="materialData" :matFilter="matFilter" :matCol="matCol"
                    :MaterialCateOption="MaterialCateOption" @row-dbclick="handleMatDbClickEX"></materialList>
                  <a-row style="text-align: center" class="btnrow">
                    <div style="margin: auto;">
                      <a-button type="primary" v-on:click="handleMatfirmEX" style="margin-top: 8px; margin-bottom: 8px">
                        <template #icon>
                          <check-outlined />
                        </template>
                        确认
                      </a-button>
                      <a-button v-on:click="handleMatCloseEX" style="margin-left: 10px;">
                        返回
                      </a-button>
                    </div>
                  </a-row>
                </a-row>
              </a-row>
            </a-row>
            <a-row v-if="showDeviceCtlModel == true" style="height: 340px;padding:5px">
              <DeviceCtlModel ref="refDevice" :modelData="modelData" :DevCtlmainColumns="DevCtlmainColumns"
                :DevMainCtrData="DevMainCtrData" :DeviceCtlParama="DeviceCtlParama" :DeviceModelCols="DeviceModelCols"
                :planDevice="planDevice" @addModel="handleAddModel" @ImportModel="handleImportModel" />
            </a-row>
            <a-row v-if="isMatFromERP && ifUseMultiMat && !showMatreial && IsMaterial" style="width: 100%;">
              <a-row style="height: 330px;border: 1px solid #d1dbe5;width: 100%;">
                <a-row style="margin-left: 10px;margin-top: 3px;width: 100%;">替换物料</a-row>
                <a-row style="width: 100%; height: calc(100% - 20px); margin: 0; padding: 0">
                  <MultiMatList :MultiMats="MultiMats" :QCItemCols="multiMatCols" :showOperate="ifCanBeEdite"
                    @delMatItem="handleDelMultiMatsItem" @addMatReplace="handleNewMultiMatsItem" :rowSelection="null">
                  </MultiMatList>
                </a-row>
              </a-row>
            </a-row>
            <a-row class="btnrow" v-if="showMatreial == false && showExpression == false">
              <div style="margin: auto;">
                <a-button type="primary" v-on:click="handleConfirm" :disabled="editFunParam.length == 0">
                  <template #icon>
                    <check-outlined />
                  </template>
                  确认
                </a-button>
                <a-button v-on:click="handleReset" :disabled="editFunParam.length == 0" style="margin-left: 10px;">
                  <template #icon>
                    <reload-outlined />
                  </template>
                  重置 </a-button>
              </div>
            </a-row>
          </a-form>
        </lt-a-form>
      </a-card>
    </a-layout-content>
    <lt-a-model v-model:open="visible" :width="800" :footer="null" :title="title" v-model:fullscreen="dlgfullscreen"
      :destroyOnClose="true">
      <DeviceCtlParamaList v-if="showParama == true" :modelData="modelData" :DevCtldetailsColumns="DevCtldetailsColumns"
        :DevCtlmainColumns="DevCtlmainColumns" :DevCtlmainFilter="DevCtlmainFilter"
        v-model:DeviceCtlParama="DeviceCtlParama" :DevMainCtrData="DevMainCtrData" :DeviceModelCols="DeviceModelCols"
        :fullscreen="dlgfullscreen" @ok="handelDlgOnOK" @deviceNameChange="handleDeviceNameChange"
        @cancel="handleDlgCancel" />
      <MultiMatDataDlg v-else-if="showMultiMatDlg" :ErpBomCols="ErpBomCols" :MultiMats="replaceMats" @ok="handelDlgOnOK"
        @dlgCancel="handleDlgCancel" @deviceNameChange="handleDeviceNameChange" :showOperate="false" :rowSelection="{
          fixed: true
        }" />
      <DlgCtrlModel v-else :modelData="modelData" :DevCtldetailsColumns="DevCtldetailsColumns"
        :DevCtlmainColumns="DevCtlmainColumns" :DevCtlmainFilter="DevCtlmainFilter"
        v-model:DeviceCtlParama="DeviceCtlParama" :DeviceModelCols="DeviceModelCols" :fullscreen="dlgfullscreen"
        :planDevice="planDevice" @ok="handelDlgOnOK" @deviceNameChange="handleDeviceNameChange"
        @cancel="handleDlgCancel" />

    </lt-a-model>
    <contextHolder />
  </a-layout>
</template>

<script setup lang="ts">
//@ts-ignore
import codeMirror from "../../../code/code-mirror.vue"; //脚本编辑器
import materialList from "./material-list.vue";
import erpBomList from "../erp-bpm-list/material-list.vue"
import Api from "../../api/api";
import EXList from "./expression-list.vue"; //表达式列表
import DeviceCtlModel from "../device-control/control-model/index.vue";
import DeviceCtlParamaList from "../device-control/control-list/index.vue";
import DlgCtrlModel from "../device-control/ctl-device-model/index.vue";
import { events } from "../../../bus";
import { watch, reactive, ref, getCurrentInstance, onMounted, onUpdated, computed, nextTick, PropType } from "vue"
import { hasRight, accSub, accAdd } from "../commonMethods/commonMethods"
import { Modal, message } from 'ant-design-vue';
import type { funParamaStruct, funOptionStruct, DeviceMainCtrDataStruct, ComBoxOptionStrct, MCIValiantOptionStruct, formularMcisItemStruct, materialItemStruct, DeviceStruct, ColStruct } from "../../../hooks/type"
import { cloneDeep } from "lodash-es";
import MultiMatList from "./multi-mat-list/list.vue";
import MultiMatDataDlg from "./multi-mat-data-dlg/index.vue";

const [contextHolder] = Modal.useModal();
const modal = ref(null)

const currentInstance = getCurrentInstance()

const props = defineProps({
  multiMatCols: {
    type: Array as PropType<ColStruct[]>,
    default() {
      return [
        {
          "Field": "MaterialCode",
          "Name": "物料编码",
          "Width": 140,
          "Fix": false,
          "Visible": true,
          "Style": "TextBox"
        },
        {
          "Field": "TechMaterialName",
          "Name": "物料型号",
          "Width": 140,
          "Fix": false,
          "Visible": true,
          "Style": "TextBox"
        },
        {
          "Field": "MaterialName",
          "Name": "物料名称",
          "Width": 140,
          "Fix": false,
          "Visible": true,
          "Style": "TextBox"
        },
        {
          "Field": "Field01",
          "Name": "备注1",
          "Width": 60,
          "Fix": false,
          "Visible": false,
          "Style": "TextBox"
        },
        {
          "Field": "Field02",
          "Name": "备注2",
          "Width": 60,
          "Fix": false,
          "Visible": false,
          "Style": "TextBox"
        },
        {
          "Field": "Field03",
          "Name": "备注3",
          "Width": 60,
          "Fix": false,
          "Visible": false,
          "Style": "TextBox"
        },
        {
          "Field": "Field_04",
          "Name": "备注4",
          "Width": 60,
          "Fix": false,
          "Visible": false,
          "Style": "TextBox"
        },
        {
          "Field": "Field05",
          "Name": "备注5",
          "Width": 60,
          "Fix": false,
          "Visible": false,
          "Style": "TextBox"
        },
      ];
    },
  },
  ifCanBeEdite: {
    type: Boolean,
    default: true,
  },
  ParamNameReplaceRelation: {
    type: Object,
    default() {
      return null
    }
  },
  formData: {
    type: Object,
    default() {
      return null;
    },
  },
  DeviceOption: {
    type: Array,
  },
  baseParameterOption: {
    type: Array as PropType<any[]>,
    default() {
      return [];
    },
  },
  funOption: {
    type: Array as PropType<funOptionStruct[]>,
    default() {
      return [];
    },
  },
  receipFunction: Object,
  moduleType: {
    type: String,
    default: "Formular",
  },
  EXItemCols: {
    type: Array,
    default() {
      return [
        {
          Field: "RecipeID",
          Name: "配方号",
          Width: 60,
          Fix: false,
          Visible: false,
          Style: "TextBox",
          isEdit: false,
        },
        {
          Field: "DetailOrderKey",
          Name: "关键字",
          Width: 60,
          Fix: false,
          Visible: false,
          Style: "TextBox",
          isEdit: false,
        },
        {
          Field: "FormularMCIId",
          Name: "序号",
          Width: 60,
          Fix: false,
          Visible: false,
          Style: "TextBox",
          isEdit: false,
        },
        {
          Field: "MaterialCode",
          Name: "材料编码",
          Width: 100,
          Fix: false,
          Visible: true,
          Style: "TextBox",
          isEdit: false,
        },
        {
          Field: "MCIValiantId",
          Name: "变量ID",
          Width: 100,
          Fix: false,
          Visible: true,
          Style: "ComBox",
          Option: [],
          isEdit: false,
        },
        {
          Field: "DefaultMCI",
          Name: "变量值",
          Width: 100,
          Fix: false,
          Visible: true,
          Style: "TextBox",
          isEdit: false,
        },
      ];
    },
  },
  MCIValiantOption: {
    type: Array as PropType<MCIValiantOptionStruct[]>,
    default() {
      return [];
    },
  },
  ifDefaultMCIReadOnly: {
    type: Boolean,
    default: true,
  },
  matFilter: {
    type: Array,
    default() {
      return [];
    },
  },
  matCol: {
    type: Array,
    default() {
      return [];
    },
  },
  MaterialCateOption: {
    type: Array,
    default() {
      return [];
    },
  },
  showTreeOperate: {
    type: Boolean,
    default: false,
  },
  ScriptVar: {
    type: Object,
    default() {
      return {};
    },
  },
  isHaveMaterial: {
    //投料工艺必须录入物料名称
    type: Boolean,
    default: true,
  },
  isMustSelectMaterialName: {
    //物料名称不可手动输入
    type: Boolean,
    default: true,
  },
  errorLimitDefaultVal: {
    type: String,
    default: "0.0005",
  },
  DevCtldetailsColumns: {
    type: Array as PropType<ColStruct[]>,
    default() {
      return [];
    },
  },
  DevCtlmainColumns: {
    type: Array as PropType<ColStruct[]>,
    default() {
      return [];
    },
  },
  DevCtlmainFilter: {
    type: Array,
    default() {
      return [];
    },
  },
  DeviceModelCols: {
    //模板详细信息
    type: Array as PropType<ColStruct[]>,
    default() {
      return [];
    },
  },
  ExpressionOption: {
    //配方公式
    type: Array as PropType<ComBoxOptionStrct[]>,
    default() {
      return [];
    },
  },
  ErpBomDetails: {
    //ERPBOM清单
    type: Array,
    default() {
      return []
    }
  },
  ErpBomCols: {
    type: Array as PropType<ColStruct[]>,
    default() {
      return []
    }
  },
  isMatFromERP: {
    type: Boolean,
    default: false
  },
  matLimitOption: {
    type: Array,
    default() {
      return []
    }
  },
  planDevice: {
    type: Array as PropType<DeviceStruct[]>,
    default() {
      return []
    }
  },
  DeviceModelMainCols: {
    //模板详细信息
    type: Array,
    default() {
      return [
        {
          Field: "DeviceId",
          Name: "ID",
          Width: 60,
          Fix: false,
          Visible: false,
          Style: "TextBox",
          isNumber: true,
        },
        {
          Field: "ModelName",
          Name: "模板名称",
          Width: 110,
          Fix: false,
          Visible: true,
          Style: "TextBox",
          Required: true,
          isNumber: false,
        },
      ];
    },
  },
  ifUseMultiMat: {
    type: Boolean,
    default: false
  },
  erpBomMatRelation: {
    type: Object,
    default() {
      return null
    }
  },
})

interface DynamicDtruct {
  [key: string]: any;
}
const emits = defineEmits(["closeParamForm"])

const refFormComFunct = ref();

let form = ref({
} as DynamicDtruct)
let RecipeStyleName = "";//投料位置名称

let FunctionCode = ref(null); //工艺代码
let CylinderClass = ref(null); //容器类型
let funParam = ref([] as funParamaStruct[])  //工艺参数
let editFunParam = ref([] as funParamaStruct[])  //编辑参数
let showFunParam = ref([] as funParamaStruct[]) //图形中显示的参数
let showMatreial = ref(false)
let materialData = ref({} as materialItemStruct) //当前选中材料

let dataStruct = reactive({} as DynamicDtruct)  //原始数据结构
let ParantID = ref(0) //投料位置
let localDetailOrderKey = ref("") //关键字
let materialFiledName = ref("")
let showExpression = ref(false)  //是否显示反编译明细表单
const title = ref("设备控制参数")

type mciDataStruct = {
  RecipeID: string,
  DetailOrderKey: number,
  FormularMCIId: number,
  MaterialCode: string,
  MCIValiantId: string,
  MCIValiantOption: any,
  DefaultMCI: any,
}

let FormularMCI = ref([] as mciDataStruct[])
let innerEXICols = ref([])
let currentEXrow = ref({} as mciDataStruct)  //当前操作的expression行
let Status = ref(0)
let selectMatType = ref("")
let bFloateCheck = ref(true)  //浮点数检查
let bIntCheck = ref(true)  //整数检查
let showDeviceCtlModel = ref(false)
let modelData = ref({})
let DeviceCtlParama = ref({} as any) //设备控制参数
let DevMainCtrData = ref([]) //设备参数基础数据
let ExpressionItemId = ref("") //当前步计算公式
let ExpressionItemName = ref("") //当前步计算公式显示值
let showExpressionOption = ref(false)   //是否显示计算公式
let functID = ref(-1)
const dlgfullscreen = ref(false)
let graph = ref(null)
let localOriginData = ref({} as any)
const DisplayMaxRow = ref(10)
const MultiMats = ref([])
const replaceMats = ref([])
const innerErpBomDetails = ref(cloneDeep(props.ErpBomDetails))
const showMultiMatDlg = ref(false)
const currentLimitOption = ref([])


// watch(() => props.ErpBomDetails, (value) => {
//   console.log("数据改变")

// })
const visible = ref(false)
const showParama = ref(false)

const funStyle = computed(() => {
  let style = -1;
  for (const i in props.funOption) {
    if (props.funOption[i].FunctionCode == FunctionCode.value) {
      style = props.funOption[i].FuncStyle;
      break;
    }
  }
  return style;
})

const showMaterailRow = computed(() => {
  let bRet = false;
  for (let i = 0; i < editFunParam.value.length; i++) {
    if (
      editFunParam.value[i].FieldName == "EditMatName" ||
      editFunParam.value[i].FieldName == "RecipeMatName" ||
      editFunParam.value[i].FieldName == "DisplayMaterialName"
    ) {
      if (editFunParam.value[i].FieldName == selectMatType.value) {
        /*eslint-disable */
        materialFiledName.value = editFunParam.value[i].ParamName;
        bRet = true;
        break;
      }
    }
  }
  return bRet;
})

const rules = computed(() => {
  let rulesTemp = {}
  for (let i = 0; i < funParam.value.length; i++) {
    if (funParam.value[i].FieldName == "ParantID") {
      //@ts-ignore
      rulesTemp[funParam.value[i].FieldName] = [
        { required: true, message: "非空值", trigger: 'change', type: 'number' },
      ]
    }
    else if (funParam.value[i].MustHaveValue == true) {
      //@ts-ignore
      rulesTemp[funParam.value[i].FieldName] = [
        { required: true, message: "非空值", trigger: 'change', type: 'string' },
      ]
    }
  }
  return rulesTemp
})

const DnyRules = function (fieldName: string) {
  let temp = [] as any[]
  const target = funParam.value.filter((item) => {
    return item.FieldName == fieldName
  })

  if (target.length > 0) {
    if (target[0].MustHaveValue == true) {
      temp = [
        { required: true, message: "非空值", trigger: 'change' },
      ]
    }
  }
  return temp
}

watch(funParam,
  (newValue) => {
    if (newValue.length < 1) {
      editFunParam.value = []; //编辑参数
      showFunParam.value = []; //页面显示参数
      return;
    }
    editFunParam.value = []; //编辑参数
    showFunParam.value = []; //页面显示参数
    showExpressionOption.value = false;
    let bmatID = hasRight("Material.matID.Look"); // EditMatName
    let bmatName =
      hasRight("Material.matName.Look") ||
      hasRight("SeeMaterialTechCode"); //RecipeMatName
    let bmatDesc = hasRight("Material.matDesc.Look"); //DisplayMaterialName
    //权限值计算
    for (let i = 0; i < newValue.length; i++) {
      if (props.moduleType == "Formular") {
        //配方的情况下
        if (newValue[i].EditProperty == 0 || newValue[i].EditProperty == 2) {
          if (
            (newValue[i].FieldName == "RecipeMatName" && bmatName == false) ||
            (newValue[i].FieldName == "DisplayMaterialName" &&
              bmatDesc == false) ||
            (newValue[i].FieldName == "EditMatName" && bmatID == false)
          ) {
            continue;
          }
          if (newValue[i].FieldName == "ExpressionItemId") {
            showExpressionOption.value = true;
          }
          editFunParam.value.push(newValue[i]); //面板属性
          // console.log(newValue[i]);
        }
        if (newValue[i].EditProperty == 1 || newValue[i].EditProperty == 0) {
          if (
            (newValue[i].FieldName == "RecipeMatName" && bmatName == false) ||
            (newValue[i].FieldName == "DisplayMaterialName" &&
              bmatDesc == false) ||
            (newValue[i].FieldName == "EditMatName" && bmatID == false)
          ) {
            continue;
          }
          showFunParam.value.push(newValue[i]); //图元显示属性
        }
      } else {
        if (
          newValue[i].DisplayProperty == 0 ||
          newValue[i].DisplayProperty == 2
        ) {
          if (
            (newValue[i].FieldName == "RecipeMatName" && bmatName == false) ||
            (newValue[i].FieldName == "DisplayMaterialName" &&
              bmatDesc == false) ||
            (newValue[i].FieldName == "EditMatName" && bmatID == false)
          ) {
            continue;
          }
          editFunParam.value.push(newValue[i]); //面板属性
        }
        if (
          newValue[i].DisplayProperty == 1 ||
          newValue[i].DisplayProperty == 0
        ) {
          if (
            (newValue[i].FieldName == "RecipeMatName" && bmatName == false) ||
            (newValue[i].FieldName == "DisplayMaterialName" &&
              bmatDesc == false) ||
            (newValue[i].FieldName == "EditMatName" && bmatID == false)
          ) {
            continue;
          }
          showFunParam.value.push(newValue[i]); //图元显示属性
        }
      }
    }
  })

watch(FunctionCode,
  (newValue) => {
    if (newValue) {
      showMatreial.value = false;
      selectMatType.value = "";
    }

    showExpression.value = false;
    FormularMCI.value = [];

    if (props.formData.EditFunName == FunctionCode.value) {
      FormularMCI.value = props.formData.FormularMCI;
    } else {
      FormularMCI.value = [];
    }
    getCurrentFunid()
  })

watch(() => props.formData, () => {
  initFormVal()
})

const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const filterFunOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const getCurrentFunid = () => {
  let id = -1
  for (const i in props.funOption) {
    if (props.funOption[i].FunctionCode == FunctionCode.value) {
      id = props.funOption[i].FuncId;
      break;
    }
  }
  if (
    props.formData.EditFunName != FunctionCode.value ||
    typeof props.formData.EditFunName == 'undefined' || !FunctionCode.value
  ) {
    getFunParam(id, props.formData.cell); //获取工艺参数

    getDeviceParama(id); //获取设备控制参数
  }
  functID.value = id
}

const IsMaterial = computed(() => {
  let isMaterial = false;
  for (let i = 0; i < props.funOption.length; i++) {
    if (props.funOption[i].FuncId == functID.value) {
      isMaterial = props.funOption[i].IsMaterial;
      break;
    }
  }
  return isMaterial;
})

const handleNewMultiMatsItem = function () {
  if (!form.value.EditMatName) {
    return message.warning("请先选择目标目标物料");
  }
  replaceMats.value = []
  let target = innerErpBomDetails.value.find((item: any) => item.MaterialCode === form.value.EditMatName)
  if (target) {
    //@ts-ignore
    replaceMats.value = target.ReplaceMaterials
  }
  title.value = "替换物料"
  visible.value = true
  showMultiMatDlg.value = true
}
const handleDelMultiMatsItem = function (row: any) {
  for (let i = 0; i < MultiMats.value.length; i++) {
    //@ts-ignore
    if (row.MaterialCode == MultiMats.value[i].MaterialCode) {
      MultiMats.value.splice(i, 1);
      break;
    }
  }
}
const getCurrentMatLimitOption = function () {
  let currentOption = [] as any
  currentOption = cloneDeep(props.matLimitOption)
  if (typeof graph.value != "undefined" && graph.value != null) {
    //@ts-ignore
    let cells = graph.value.getModel().cells
    for (let j = 0; j < currentOption.length; j++) {
      let totalWeight = 0
      let MaterialCode = currentOption[j].MaterialCode
      for (const i in cells) {
        if (typeof cells[i].cellType == "undefined") {
          continue;
        }
        if (cells[i].IsAdjust && cells[i].DetailOrderKey != form.value.DetailOrderKey) {
          if (cells[i].cellType == "Table") {
            for (let k = 0; k < cells[i].EditCols.length; k++) {
              if (cells[i].EditCols[k].EditMatName == MaterialCode) {
                totalWeight = accAdd(
                  totalWeight,
                  parseFloat(typeof cells[i].EditCols[k].EditTargetVal == 'undefined' || cells[i].EditCols[k].EditTargetVal == "" ? 0 : cells[i].EditCols[k].EditTargetVal)
                );
              }

            }
          } else {
            if (cells[i].IsMaterial == true || cells[i].IsMaterial == 1) {
              if (cells[i].EditMatName == MaterialCode) {
                if (cells[i].EditTargetVal != undefined) {
                  totalWeight = accAdd(
                    totalWeight,
                    parseFloat(typeof cells[i].EditTargetVal == 'undefined' || cells[i].EditTargetVal == "" ? 0 : cells[i].EditTargetVal)
                  );
                }
              }
            }
          }
        }
      }
      currentOption[j].HighWeight = accSub(currentOption[j].HighWeight, totalWeight)
      let targetMat = innerErpBomDetails.value.filter((item: any) => {
        return item.MaterialCode == MaterialCode
      })
      if (targetMat.length > 0) {
        //@ts-ignore
        targetMat[0].HighWeight = currentOption[j].HighWeight
      }
    }
    currentLimitOption.value = currentOption
  }
}

const initFormVal = function () {

  const newValue = props.formData
  if (newValue) {
    let cell = newValue.cell;
    graph.value = newValue.graph;
    if (cell.cellType == "Common") {
      localOriginData.value = cell
      RecipeStyleName = cell.RecipeStyleName;
      ParantID.value = cell.RecipeStyle;
      form.value.ParantID = ParantID.value
      localDetailOrderKey.value = cell.DetailOrderKey;
      MultiMats.value = (cell.MultiMats ? cell.MultiMats : [])

      ExpressionItemId.value = cell.ExpressionItemId
        ? cell.ExpressionItemId
        : "";
      ExpressionItemName.value = cell.ExpressionItemName
        ? cell.ExpressionItemName
        : "";
      Status.value = cell.Status == undefined ? "" : cell.Status;
      if (cell.value == "" || cell.value == null) {
        FunctionCode.value = null;
        CylinderClass.value = null
        getFunParam(functID.value);
      } else {
        showExpression.value = false;
        FunctionCode.value =
          typeof cell.EditFunName == "undefined" ||
            cell.EditFunName == ""
            ? null
            : cell.EditFunName;
        CylinderClass.value =
          typeof cell.CylinderClass == "undefined" ||
            cell.CylinderClass == ""
            ? null
            : cell.CylinderClass;
        getFunIDByCode()
        getFunParam(functID.value, cell);
        if (typeof cell.FormularMCI != "undefined") {
          FormularMCI.value = cell.FormularMCI;
        } else {
          FormularMCI.value = [];
        }

        if (typeof cell.DeviceCtlParama != "undefined") {
          DeviceCtlParama.value = { Items: [] };
          DeviceCtlParama.value.Items = cell.DeviceCtlParama.Items

          showDeviceCtlModel.value = true;
        } else {
          DeviceCtlParama.value = {};
          showDeviceCtlModel.value = false;
        }

      }
      getCurrentMatLimitOption()
    }
  }
}

const handleUpdateForm = function (value: DynamicDtruct) {
  //通过update来获取数据更新
  for (let i in value) {
    //@ts-ignore
    form.value[i] = value[i]
  }
}

const formatDeviceModuleData = function (data: any) {
  let tempdata = {
    ModelName: "",
    DeviceId: data.DeviceId,
    DeviceParamId: data.DeviceParamId,
    Items: [],
  };
  for (let i = 0; i < data.Options.length; i++) {
    let temp = {
      DeviceParamId: data.Options[i].MapId,
      ParamStyleName: data.DeviceParamId,
      ParamName: data.Options[i].Description,
      Value: null,
      FormularDeviceID: i,
    };
    const copy = cloneDeep(temp)
    //@ts-ignore
    tempdata.Items.push(copy);
  }
  return tempdata;
}
const handleAddModel = function () {
  //显示基础参数
  visible.value = true
  showParama.value = true
  nextTick(() => {
    showParama.value = true
  });
}
const handleImportModel = function () {
  visible.value = true
  nextTick(() => {
    showParama.value = false
  });
}
const handelDlgOnOK = function (row: any, type: string) {

  switch (type) {
    case "parama": {
      modelData.value = formatDeviceModuleData(row);
      visible.value = false
      break;
    }
    case "model": {
      modelData.value = row;
      visible.value = false
      break
    }
    case "MultiMat": {
      for (let i = 0; i < row.length; i++) {
        let temp = MultiMats.value.find((item: any) => item.MaterialCode === row[i].MaterialCode)
        if (!temp) {
          //@ts-ignore
          MultiMats.value.push({
            MaterialCode: row[i].MaterialCode,
            MaterialName: row[i].MaterialName,
            TechMaterialName: row[i].TechMaterialName,
            Field01: row[i].Field01,
            Field02: row[i].Field02,
            Field03: row[i].Field03,
            Field04: row[i].Field04,
            Field05: row[i].Field05,
          })
        }
      }
      visible.value = false
    }
  }
  title.value = "设备控制参数"
}
const handleDlgCancel = function () {
  visible.value = false
}
const handleDeviceNameChange = function (value: string) {
  //设备名称改变事件
  getDeviceParama(functID.value, value);
}

const showInput = function (value: funParamaStruct) {
  if (value.ParamStyle != 2) {
    if (
      value.FieldName != "EditMatName" &&
      value.FieldName != "DisplayMaterialName" &&
      value.FieldName != "RecipeMatName"
    ) {
      return true;
    } else {
      if (
        value.FieldName == "EditMatName" &&
        (hasRight("SeeMaterialTechCode") ||
          hasRight("Material.matID.Look"))
      ) {
        return true;
      }
      if (
        value.FieldName == "DisplayMaterialName" &&
        hasRight("Material.matDesc.Look")
      ) {
        return true;
      }
      if (
        value.FieldName == "RecipeMatName" &&
        hasRight("Material.matName.Look")
      ) {
        return true;
      }
    }
  } else {
    return false;
  }
}

const handleInputSelect = function (item: funParamaStruct) {
  //主控参数改变了，受控对象必须要清空，防止数据出现异常匹配的情况
  if (item.ChildItemFields) {
    for (let i = 0; i < item.ChildItemFields.length; i++) {
      form.value[item.ChildItemFields[i]] = ""
    }
  }
}

const showSelect = function (value: funParamaStruct) {
  //20241106新增下拉选项类型
  if (value.ParamStyle == 2) {
    return true
  } else {
    return false
  }
}
const showCommonSelect = function (value: funParamaStruct) {
  return typeof value.ItemFilterField == "undefined" || value.ItemFilterField == "" || value.ItemFilterField == null || value.ItemFilterField.length == 0
}
const getSelectItems = function (item: funParamaStruct) {
  if (typeof form.value[item.ItemFilterField] != "undefined" && form.value[item.ItemFilterField] != "") {
    return item.SelectItems.filter((list) => {
      return list.FilterValue.indexOf(parseInt(form.value[item.ItemFilterField])) != -1 || list.FilterValue == null
    })
  } else {
    return item.SelectItems
  }
}

const _getReadOnlyItem = function (FieldName: string) {
  if (FieldName == "ParantID") {
    return true;
  }
  if (Status.value == 1) {
    if (
      FieldName == "EditTargetVal" ||
      FieldName == "TargetVal" ||
      FieldName == "RemarkValue" ||
      FieldName == "RemarkValue2" ||
      FieldName == "EidtFunTargetVal" ||
      FieldName == "AdjustStatus" ||
      FieldName == "ErrorLimit" //||
      // FieldName == "DisplayMaterialName" ||
      // FieldName == "RecipeMatName"
    ) {
      return false;
    } else {
      return true;
    }
  }
  return false;
}
const getFormatOption = function () {
  let tempArray = [];
  let opton = props.MCIValiantOption;
  for (let i = 0; i < opton.length; i++) {
    let temp = {
      ParamValue: opton[i].PropertyId,
      ParamName: opton[i].Description,
    };
    let copy = cloneDeep(temp);;
    tempArray.push(copy);
  }
  return tempArray;
}
const handleMciChnage = function (row: any) {
  currentEXrow.value = row;
  //@ts-ignore
  FormularMCI.value = currentInstance.refs.refexlist.getMciData();
  showExpression.value = true;
}
const handleExpresChange = function (key: string) {
  let TargetVal = props.ExpressionOption.filter((item) => {
    return item.key == key;
  });
  if (TargetVal.length > 0) {
    ExpressionItemName.value = TargetVal[0].label;
  } else {
    ExpressionItemName.value = ""
  }
}

const handleMatfirm = function () {
  if (materialData.value == null) {
    Modal.warning({
      content: "请先选择物料!",
      title: "警告"
    })
    return;
  }
  form.value.EditMatName = materialData.value.MaterialCode; //物料编码
  form.value.DisplayMaterialName = materialData.value.MaterialName; //物料名称
  form.value.RecipeMatName = materialData.value.TechMaterialName; //技术部专用名称
  //从ERP过来的单据，前端先写死，如果后面有需要，可以在配置列里面增加映射
  if (materialData.value.MatStandant) {
    //ERPbom里面过来的标准用量
    form.value.EditTargetVal = materialData.value.MatStandant
  }
  if (materialData.value.MatErrorLimit) {
    form.value.ErrorLimit = materialData.value.MatErrorLimit
  }
  showMatreial.value = false;
  selectMatType.value = "";
}
const handleMatfirmEX = function () {
  if (materialData.value == null) {
    Modal.warning({
      content: "请先选择物料!",
      title: "警告"
    })
    return;
  }
  for (const i in FormularMCI.value) {
    if (
      FormularMCI.value[i].FormularMCIId == currentEXrow.value.FormularMCIId
    ) {
      FormularMCI.value[i].MaterialCode = materialData.value.MaterialCode;
      showExpression.value = false;
      break;
    }
  }
  showExpression.value = false;
}
const handleMatClose = function () {
  //关闭材料面板
  showMatreial.value = false;
  selectMatType.value = "";

}
const handleMatCloseEX = function () {
  showExpression.value = false;
}
const formateEXIndex = function () {
  for (let i = 0; i < FormularMCI.value.length; i++) {
    //在提交数据之前，对id进行整理
    //@ts-ignore
    FormularMCI.value[i].FormularMCIId = i + 1;
    //@ts-ignore
    FormularMCI[i].value.DetailOrderKey = localDetailOrderKey.value;
  }
}
const handleConfirm = function () {
  form.value.ParantID = ParantID.value; //提交数据的时候，赋值parentID
  refFormComFunct.value
    .validate()
    .then((data: any) => {
      if (data) {
        //确认修改数据
        form.value.EditFunName = FunctionCode.value;
        form.value.CylinderClass = CylinderClass.value;
        if (CylinderClass.value === undefined || CylinderClass.value === '' || CylinderClass.value === null) {
          if (!form.value.EditMatName) {
            delete form.value.CylinderClass
          }
        }
        form.value.DetailOrderKey = localDetailOrderKey.value;
        form.value.ExpressionItemId = ExpressionItemId.value;
        form.value.ExpressionItemName = ExpressionItemName.value;
        form.value.IsMaterial = IsMaterial.value;
        form.value.MultiMats = MultiMats.value
        if (showDeviceCtlModel.value == true) {
          //@ts-ignore
          form.value.DeviceCtlParama = currentInstance.refs.refDevice.getDeviceCtlData();
          form.value.showDeviceCtlModel = showDeviceCtlModel.value;
        }


        if (funStyle.value == 25 || funStyle.value == 26) {
          formateEXIndex();
          //var temp = currentInstance.refs.refexlist.getMciData();
          //@ts-ignore
          form.value.FormularMCI = currentInstance.refs.refexlist.getMciData();
        }

        if (
          form.value.EditTargetVal != undefined &&
          props.formData.RealValue != undefined
        ) {
          if (
            accSub(props.formData.RealValue, form.value.EditTargetVal) > Number.EPSILON
          ) {
            Modal.warning({
              content: "目标量不能小于实际量!",
              title: "警告"
            })
            form.value.EditTargetVal = props.formData.RealValue;
            return;
          }
        }
        if (typeof form.value.TargetVal != 'undefined' && props.formData.RealValue) {
          if (accSub(props.formData.RealValue, form.value.TargetVal) > Number.EPSILON) {
            form.value.TargetVal = props.formData.RealValue;
            Modal.warning({
              content: "目标量不能小于实际量!",
              title: "警告"
            })
            return;
          }
        }
        if (IsMaterial.value == true && props.isHaveMaterial == true) {
          //化工必须录入物料名称
          if (
            form.value.EditMatName == "" ||
            form.value.EditMatName == null ||
            typeof form.value.EditMatName == 'undefined'
          ) {
            Modal.warning({
              content: "物料名称不能为空!",
              title: "警告",
              onOk: async () => {
                // await Promise.resolve();
                // modal.value.destroy();
              }
            })
            return;
          }
        }

        if (IsMaterial.value == true) {
          //如果当前工艺是物料的话，则给允许误差赋值
          if (
            typeof form.value.ErrorLimit == 'undefined' ||
            form.value.ErrorLimit == "" ||
            form.value.ErrorLimit == null ||
            accSub(form.value.ErrorLimit, 0.000001) < 0.0001
          ) {
            form.value.ErrorLimit = props.errorLimitDefaultVal;
          }
        }

        if (bFloateCheck.value == false) {
          Modal.warning({
            content: "请检查页面浮点数格式",
            title: "警告"
          })
          return;
        }

        if (bIntCheck.value == false) {
          Modal.warning({
            content: "请检查页面整数格式",
            title: "警告"
          })
          return;
        }

        if (IsMaterial.value == true) {
          form.value.TargetVal =
            typeof form.value.EditTargetVal == 'undefined' ? 0 : form.value.EditTargetVal;
        } else {
          form.value.TargetVal =
            typeof form.value.EidtFunTargetVal == 'undefined'
              ? 0
              : form.value.EidtFunTargetVal;
        }

        if (props.matLimitOption.length > 0) {
          //如果物料限制长度大于零，则需要对物料加料量进行检查，只用于改单情况下
          if (!checkLimitMatWeight()) {
            return
          }
          form.value.IsAdjust = true //需要打上调整标志
        }

        checkIsMatChange()


        let sendData = {
          showData: showFunParam.value,
          validData: form.value,
          Descript: getFunNameByFunID(functID.value),
          DisplayMaxRow: DisplayMaxRow.value
        };
        //@ts-ignore
        sendData.validData.DisplayMaxRow = DisplayMaxRow.value
        const propertyData = {
          data: sendData,
          type: "Common", //标准工艺
        };

        events.emit("porpertyChange", propertyData);
        handleReset(); //数据推送之后清空面板
        emits("closeParamForm", 1);
      }
    }).catch((error: any) => {
      message.warn("请检查页面必输项")
    })
}

const checkLimitMatWeight = function () {
  //判断当前物料的上限有没有超
  let MaterialCode = form.value.EditMatName
  let targetMat = props.matLimitOption.filter((item: any) => {
    return item.MaterialCode == MaterialCode
  })
  let bRet = true
  let highrLimit = 0

  if (targetMat.length == 0) {
    return bRet
  } else {
    //@ts-ignore
    highrLimit = targetMat[0].HighWeight
  }
  if (graph.value) {
    //@ts-ignore
    let cells = graph.value.getModel().cells
    let totalWeight = 0
    for (let i in cells) {
      if (typeof cells[i].cellType == "undefined") {
        continue;
      }
      if (cells[i].IsAdjust && cells[i].DetailOrderKey != localDetailOrderKey.value) {
        if (cells[i].cellType == "Table") {
          for (let j = 0; j < cells[i].EditCols.length; j++) {
            if (cells[i].EditCols[j].EditMatName == MaterialCode) {
              totalWeight = accAdd(
                totalWeight,
                parseFloat(typeof cells[i].EditCols[j].EditTargetVal == 'undefined' || cells[i].EditCols[j].EditTargetVal == "" ? 0 : cells[i].EditCols[j].EditTargetVal)
              );
            }
          }
        } else {
          if (cells[i].IsMaterial == true || cells[i].IsMaterial == 1) {
            if (cells[i].EditMatName == MaterialCode) {
              if (typeof cells[i].EditTargetVal != 'undefined') {
                totalWeight = accAdd(
                  totalWeight,
                  parseFloat(typeof cells[i].EditTargetVal == 'undefined' || cells[i].EditTargetVal == "" ? 0 : cells[i].EditTargetVal)
                );
              }
            }
          }
        }
      }
    }
    if (accAdd(totalWeight, form.value.EditTargetVal) > highrLimit) {
      let currentlimit = totalWeight == 0 ? highrLimit : accSub(highrLimit, totalWeight)
      Modal.warning({
        title: "警告",
        content: "当前物料已超限，当前最大物料加入量为" + currentlimit
      })

      bRet = false
    }
  }
  return bRet
}

const checkIsMatChange = function () {
  if (localOriginData.value.EditMatName) {
    if (localOriginData.value.EditMatName != form.value.EditMatName) {
      form.value.DetailOrderKey = null;
      form.value.keyWord = null
    }
  }
}
const handleReset = function () {
  //初始化的时候，将页面初始化成初始结构
  form.value = cloneDeep(dataStruct)
  form.value.ParantID = props.formData.RecipeStyle;
  MultiMats.value = []
}

const getFunNameByFunID = function (value: number) {
  let name = "";
  if (value == -1) {
    return "物料计量";
  }
  for (let i = 0; i < props.funOption.length; i++) {
    if (props.funOption[i].FuncId == value) {
      name = props.funOption[i].FunctionName2;
      break;
    }
  }
  return name;
}
const handleFoucus = function (value: any, type?: string) {
  if (props.isMustSelectMaterialName == false && typeof type == 'undefined') {
    showMatreial.value = false;
    return;
  }
  if (
    value == "EditMatName" ||
    value == "DisplayMaterialName" ||
    value == "RecipeMatName"
  ) {
    if (Status.value == 1) {
      showMatreial.value = false;
    } else {
      selectMatType.value = value;
      showMatreial.value = true;
    }
  } else {
    selectMatType.value = "";
    showMatreial.value = false;
  }
}
const handleInput = function (value: any) {
  //此处强制更新视图

}
const handleMatDbClick = function (row: any, dataIndex: number, event: any) {
  //双击材料行
  form.value.EditMatName = row.MaterialCode;
  form.value.DisplayMaterialName = row.MaterialName ? row.MaterialName : "";
  form.value.RecipeMatName = row.TechMaterialName;
  //从ERP过来的单据，前端先写死，如果后面有需要，可以在配置列里面增加映射
  if (row.ERPRowID) {
    form.value.ERPRowID = row.ERPRowID
  }
  if (row.RatioValue) {
    form.value.RatioValue = row.RatioValue
  }
  if (row.MatStandant) {
    //ERPbom里面过来的标准用量
    form.value.EditTargetVal = row.MatStandant
  }
  if (row.MatErrorLimit) {
    form.value.ErrorLimit = row.MatErrorLimit
  }
  if (row.ERPRowID) {
    if (props.erpBomMatRelation) {
      for (let key in props.erpBomMatRelation) {
        form.value[key] = row[props.erpBomMatRelation[key]]
      }
    }
  }

  showMatreial.value = false;
  selectMatType.value = "";
  if (props.ifUseMultiMat) {
    replaceMats.value = []
    let target = innerErpBomDetails.value.find((item: any) => item.MaterialCode === form.value.EditMatName)
    if (target) {
      //@ts-ignore
      replaceMats.value = target.ReplaceMaterials
    }
    //@ts-ignore
    MultiMats.value = replaceMats.value.map((item: any) => {
      return {
        MaterialCode: item.MaterialCode,
        MaterialName: item.MaterialName,
        TechMaterialName: item.TechMaterialName,
        Field01: item.Field01,
        Field02: item.Field02,
        Field03: item.Field03,
        Field04: item.Field04,
        Field05: item.Field05,
      }
    })
  }
  getCurrentMatLimitOption()

}
const handleMatDbClickEX = function (row: any, dataIndex: number, event: any) {
  //表达式选择材料
  for (const i in FormularMCI.value) {
    if (
      FormularMCI.value[i].FormularMCIId == currentEXrow.value.FormularMCIId
    ) {
      FormularMCI.value[i].MaterialCode = row.MaterialCode;
      showExpression.value = false;
      break;
    }
  }
  showExpression.value = false;
}

const getFunIDByCode = function () {
  var id = -1;
  for (const i in props.funOption) {
    if (props.funOption[i].FunctionCode == FunctionCode.value) {
      id = props.funOption[i].FuncId;
      break;
    }
  }
  console.log("计算的ID结果是：" + id);
  functID.value = id;
}

const getFunParam = function (functID: number, parentData?: any) {
  Api.LoadFunctionParam(functID)
    .then((data: any) => {
      if (data.Params.length < 1) return;
      if (props.ParamNameReplaceRelation) {
        for (let key in props.ParamNameReplaceRelation) {
          let target = data.Params.find((item: any) => item.FieldName === key)
          if (target) {
            target.ParamName = props.ParamNameReplaceRelation[key]
          }
        }
      }
      funParam.value = data.Params;
      DisplayMaxRow.value = data.DisplayMaxRow ? data.DisplayMaxRow : 10
      formatDataStruct(funParam.value, parentData);
    })
    .catch((err: any) => {
      //提交失败的时候，直接抛出后台报错
      // message.error({
      //   content: err
      // })
    });
}
const getDeviceParama = function (functID: number, deviceName?: string) {
  let sendData = {
    DeviceId: 0,
    FunctionId: functID,
    IsCheck: false,
    RecipeStyle: props.formData.ParantID,
    DeviceName: typeof deviceName == "undefined" ? null : deviceName,
  };

  Api.LoadDeviceCtlParama(sendData)
    .then((data: any) => {
      showDeviceCtlModel.value = false
      if (data.Params.length > 0) {
        showDeviceCtlModel.value = true;
        DevMainCtrData.value = []
        for (let i = 0; i < data.Params.length; i++) {
          //@ts-ignore
          DevMainCtrData.value.push(data.Params[i])
        }

        nextTick(() => {
          showDeviceCtlModel.value = true;
        })
      } else {
        showDeviceCtlModel.value = false;
      }

    })
    .catch((err: any) => {
      //提交失败的时候，直接抛出后台报错
      // message.error({
      //   content: err
      // })
    });
}
const formatDataStruct = function (data: any, parentData?: any) {
  //根据接口，初始化form结构
  if (data.length < 1) {
    //如果工艺参数没有设置
    dataStruct = {} as DynamicDtruct;
    //form.value = reactive(cloneDeep(dataStruct))
    return;
  }
  for (let i = 0; i < data.length; i++) {
    dataStruct[data[i].FieldName] = "";
    dataStruct.FormularMCI = [];
    if (IsMaterial.value == true) {
      form.value.DisplayMaterialName =
        typeof props.formData.DisplayMaterialName == 'undefined'
          ? ""
          : props.formData.DisplayMaterialName;
      form.value.EditMatName =
        typeof props.formData.EditMatName == 'undefined'
          ? ""
          : props.formData.EditMatName;
      form.value.RecipeMatName =
        typeof props.formData.RecipeMatName == 'undefined'
          ? ""
          : props.formData.RecipeMatName;
    }
    form.value = cloneDeep(dataStruct)
  }

  //form = reactive(cloneDeep(dataStruct))
  if (typeof parentData != 'undefined') {
    for (const j in form.value) {
      form.value[j] = typeof parentData[j] == 'undefined' ? "" : parentData[j];
    }
  }

  form.value.ParantID = props.formData.cell.RecipeStyle;
}

const getEXICloumn = function () {
  //@ts-ignore
  innerEXICols.value = cloneDeep(props.EXItemCols)
  for (const i in innerEXICols.value) {
    //@ts-ignore
    if (innerEXICols.value[i].Field == "MCIValiantId") {
      //@ts-ignore
      innerEXICols.value[i].Option = getFormatOption();
    }
    if (
      //@ts-ignore
      innerEXICols.value[i].Field == "MaterialCode" ||
      //@ts-ignore
      innerEXICols.value[i].Field == "MCIValiantId"
    ) {
      //@ts-ignore
      innerEXICols.value[i].isEdit = props.showTreeOperate;
    }
    //@ts-ignore
    if (innerEXICols.value[i].Field == "DefaultMCI") {
      //@ts-ignore
      innerEXICols.value[i].isEdit = !props.showTreeOperate;
    }
  }
}
const strlen = function (str: string) {
  if (str == null) return 0;
  if (typeof str != "string") {
    str = str + "";
  }
  const len = str.replace(/[^\x00-\xff]/g, "01").length;

  return len;
}


onMounted(() => {
  initFormVal()
  getEXICloumn();
  getDeviceParama(functID.value); //获取设备控制参数
})
onUpdated(() => {

  console.log("执行onUpdated")
  const temp = $("#refFormComFunct").find(".a-row:last-child");
  const row = $("#refFormComFunct")
    .find(".a-row")
    .each(function () {
      this.style.width = "100%"
      if (this.children.length < 1) {
        this.style.borderBottom = "0px";
      } else {
        this.style.borderBottom = "1px solid #d1dbe5";
        const lastRow = $("#refFormComFunct")
          .find(".a-row:last-child")
          .each(function () {
            this.style.borderBottom = "0px solid #d1dbe5";
          });
      }
    });
})
</script>

<style scoped>
.header-bread {
  margin-top: 8px;
  margin-left: 10px;
  font-size: 16px;
  font-weight: bold;
}

.codeRow {
  height: 500px;
}

.ltui-form label.a-form-item__label {
  overflow: hidden !important;
}
</style>
<style>
.btnrow {
  text-align: center;
  /* border-left: 1px solid #d1dbe5 !important; */
  padding: 5px;
  display: flex;
}

#refFormComFunct .ant-form-item,
#refFormComFunct .ltaui-form {
  border-left: 0px !important;
}
</style>
