<template>
  <a-layout style="height: 100%; padding: 5px; padding-left: 0px; min-width: 430px">
    <a-layout-content style="padding: 5px; height: 100%; border: 1px solid #d1dbe5">
      <a-card class="box-card" style="padding: 0px; height: 99.8%" :body-style='{ padding: "5px", height: "99%" }'>
        <lt-a-form contendPadding="5px" :fill="true" :fit="false" style="border-width: 0px; height: 100%">
          <a-form ref="refFormMatTable" :inline="false" id="refFormMatTable" :model="form" :inline-message="true"
            label-width="100px" style="width: 100%;" :labelCol="{
              span: 6
            }">
            <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 style="height: 500px;" v-if="showMatreial == false">
              <div style="width: 100%;height: 500px;padding: 2px;">
                <lt-a-table :dataSource="materialDatas" :show-overflow-tooltip="true" ref="refTableMatGroup"
                  id="refTableMatGroup" :searchBox="false" fill :fit="false" style="border: 0px; " bordered
                  :highlight-current-row="true" :pagination="false" :showToolBar="false" size="small"
                  :showEditInDialog="false" :columns="columns">
                  <template #headerCell="{ column }">
                    <template v-if="column.dataIndex === 'operate'">
                      <span>
                        <a-button type="text" title="新增" size="small"
                          style=" color: dodgerblue;font-weight: bold;margin: 0px;" @click="handleAddMatDatas">
                          <template #icon>
                            <i class="icon icon-plus "></i>
                          </template>
                        </a-button>
                      </span>
                    </template>
                  </template>
                </lt-a-table>
              </div>
            </a-row>
            <a-row v-if="showMatreial == true" style="width: 100%;">
              <a-row style="height: 342px;width: 100%;padding: 2px;">
                <erpBomList v-if="isMatFromERP == true" v-model:selectRowData="erpBomData"
                  v-model:selectionData="materialCheckData" :matFilter="matFilter" :ErpBomCols="ErpBomCols"
                  :ErpBomDetails="ErpBomDetails" :showCheck="true" @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;padding: 5px;display: flex;width: 100%;">
                <div style="margin: auto;text-align: center;">
                  <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
              style="text-align: center; border-bottom-width: 1px !important;padding: 5px;display: flex;border-top: 1px solid #d1dbe5;"
              v-if="showMatreial == false">
              <div style="margin: auto;">
                <a-button v-on:click="handleConfirm" type="primary" :disabled="editFunParam.length == 0">
                  <template #icon>
                    <check-outlined />
                  </template>确认</a-button>
                <a-button v-on:click="handleReset" :disabled="editFunParam.length == 0">
                  <template #icon>
                    <reload-outlined />
                  </template>
                  重置</a-button>
              </div>
            </a-row>
          </a-form>
        </lt-a-form>
      </a-card>
    </a-layout-content>
  </a-layout>
</template>

<script setup lang="tsx">
import materialList from "../material-list.vue";
import erpBomList from "../../erp-bpm-list/material-list.vue"
import Api from "../../../api/api";
import { events } from "../../../../bus"
import { reactive, ref, computed, watch, onBeforeMount, PropType } from "vue";
import { hasRight, GuidID, accSub, accAdd } from "../../commonMethods/commonMethods"
import { Modal } from "ant-design-vue";
import type { funParamaStruct, funOptionStruct, MCIItemStruct, ComBoxOptionStrct, MCIValiantOptionStruct, formularMcisItemStruct, materialItemStruct, ColStruct } from "../../../../hooks/type"
import { cloneDeep } from "lodash-es";
const props = defineProps({
  ParamNameReplaceRelation: {
      type: Object,
      default() {
        return null
      }
    },
  formData: {
    type: Object,
    default() {
      return null;
    },
  },
  DeviceOption: {
    type: Array,
  },
  funOption: {
    type: Array as PropType<funOptionStruct[]>,
    default() {
      return [];
    },
  },
  receipFunction: Object,
  moduleType: {
    type: String,
    default: "Formular",
  },
  MCIValiantOption: {
    type: Array,
    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,
    default() {
      return [];
    },
  },
  DevCtlmainColumns: {
    type: Array,
    default() {
      return [];
    },
  },
  DevCtlmainFilter: {
    type: Array,
    default() {
      return [];
    },
  },
  DeviceModelCols: {
    //模板详细信息
    type: Array,
    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 []
    }
  }
})

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

interface materailFunStruct{
  Key:string
  Label:string
}
let form = reactive({} as DynamicDtruct)
let RecipeStyleName = ref("") //投料位置名称
let FunctionCode = ref(null)  //工艺代码
let funParam = ref([] as funOptionStruct[]) //工艺参数
let editFunParam = ref([] as funParamaStruct[]) //编辑参数
let showFunParam = ref([] as funParamaStruct[]) //图形中显示的参数
let showMatreial = ref(false)
let materialData = ref({} as materialItemStruct)//当前选中材料
let materialCheckData = ref([] as materialItemStruct[])

let dataStruct = reactive({} as DynamicDtruct)  //原始数据结构
let ParantID = ref("") //投料位置

let editClos = ref([])
let materialDatas = ref([] as materialItemStruct[]) //需要提交到后台显示的数据
let selectRow = ref({} as materialItemStruct)//当前选中的行信息
let showColDatas = ref([] as materialItemStruct[]) //界面实际显示数据
let erpBomData = ref(null)
let functID = -1
let Status = ref(0)
let graph = ref(null)
let localOriginData = ref([] as materialItemStruct[]) //保存原始数据

const DetailOrderKey=ref("")
const cellID = ref("")

const columns = computed(() => {
  return editClos.value
})


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

const initFormVal = function () {
  const newValue = props.formData
  const cell = newValue.cell;
  graph.value = newValue.graph;
  if (cell && typeof cell != 'undefined') {
    if (cell.cellType == "Table") {
      cellID.value = cell.id;
      RecipeStyleName.value = cell.RecipeStyleName;
      ParantID.value = cell.RecipeStyle;
      Status.value = typeof cell.Status == 'undefined' ? "" : cell.Status;
      DetailOrderKey.value = cell.DetailOrderKey ? cell.DetailOrderKey : cell.keyWord
      if (cell.EditCols) {
        // materialDatas.value = cell.EditCols;
        $.extend(true, materialDatas.value, cell.EditCols)
        $.extend(true, localOriginData.value, cell.EditCols)
      } else {
        materialDatas.value = [];
      }
      //界面实际显示数据
      if (cell.showCols) {
        showColDatas.value = cell.showCols;
      } else {
        showColDatas.value = [];
      }
      getFunParam(functID, cell);
    }
  }
}

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 MaterialFunOption = computed(() => {
  let tempArray = [];
  for (let i = 0; i < props.funOption.length; i++) {
    if (props.funOption[i].IsMaterial == true) {
      if (!props.funOption[i].FunctionCode) {
        continue;
      }

      let temp = {
        Key: props.funOption[i].FunctionCode,
        Label: props.funOption[i].FunctionName2,
      };
      let copy = {};
      $.extend(true, copy, temp);
      tempArray.push(copy);
    }
  }
  return tempArray;
})

const ExpressionNameOption = computed(() => {
  let tempArray = [];
  for (let i = 0; i < props.ExpressionOption.length; i++) {
    let temp = {
      Key: props.ExpressionOption[i].key,
      Label: props.ExpressionOption[i].label,
    };
    let copy = {};
    $.extend(true, copy, temp);
    tempArray.push(copy);
  }
  return tempArray;
})

watch(()=>funParam.value, (newValue:any) => {
  if (newValue.length < 1) {
    editFunParam.value = []; //编辑参数
    showFunParam.value = []; //页面显示参数
    return;
  }

  editFunParam.value = []; //编辑参数
  showFunParam.value = []; //页面显示参数
  const bmatID = hasRight("Material.matID.Look"); // EditMatName
  const bmatName =
    hasRight("Material.matName.Look") ||
    hasRight("SeeMaterialTechCode"); //RecipeMatName
  const 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;
        }
        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(()=>editFunParam.value, (value:any) => {
  //初始化操作列
  editClos.value = [//@ts-ignore
    {
      
      title: '操作',
      align: 'center',
      dataIndex: 'operate',
      fixed: 'left',
      width: 65,
      customRender: ({ record, rowIndex, column }:any) => {
        return getDelBtn(record)
      }
    }
  ];

  for (let i = 0; i < value.length; i++) {
    if (value[i].FieldName == "ParantID") {
      continue;
    }
    if (value[i].FieldName == "EditFunName") {
      let temp = {
        dataIndex: value[i].FieldName,
        title: value[i].Unit
          ? value[i].ParamName + "(" + value[i].Unit + ")"
          : value[i].ParamName,
        width: 100,
        customRender: function (record:any) {
          let currecord = record.record
          let curCols = record.column
          return <a-select
            placeholder=""
            size="small"
            allowClear
            style={"width:'100%'"}
            v-model:value=
            {
              currecord[curCols.dataIndex]
            }
          >
            {
              _getMatOption()
            }
          </a-select>
        }
      }
      const copy=cloneDeep(temp)
      //@ts-ignore
      editClos.value.push(copy);
    } else if (value[i].FieldName == "ExpressionItemId") {
      let temp = {
        dataIndex: value[i].FieldName,
        title: value[i].Unit
          ? value[i].ParamName + "(" + value[i].Unit + ")"
          : value[i].ParamName,
        width: 100,
        customRender: function (record:any) {
          let currecord = record.record
          let curCols = record.column
          return <a-select
            placeholder=""
            size="small"
            allowClear
            style={"width:'100%'"}
            v-model:value=
            {
              currecord[curCols.dataIndex]
            }
          >
            {
              _getExpressionOption()
            }
          </a-select>
        }
      };
      const copy=cloneDeep(temp)
      //@ts-ignore
      editClos.value.push(copy);
    } else if (value[i].ParamStyle == 2) {

          let temp = {
            dataIndex: value[i].FieldName,
            title: value[i].Unit
              ? value[i].ParamName + "(" + value[i].Unit + ")"
              : value[i].ParamName,
            Width: 100,
            Fix: false,
            Visible: true,
            customRender: function (record:any) {
              const curCols = record.column
          const cueRecord = record.record
              if(typeof value[i].ItemFilterField == "undefined" || value[i].ItemFilterField == "" || value[i].ItemFilterField == null || value[i].ItemFilterField.length == 0){
                return <a-select size="small" v-model:value=
                {
                  cueRecord[curCols.dataIndex]
                }
                onChange={handleInputSelect(value[i])}
                      style="width: 100%;" allowClear>
                      {
                        getCommonSelectOption(value[i].SelectItems)
                      }
                    </a-select>
              }else{
                <a-select size="small" v-model:value=
                {
                  cueRecord[curCols.dataIndex]
                } style="width: 100%;"
                      allowClear>
                      {getCommonSelectOption(getSelectItems(value[i]))}
                    </a-select>
              }
            }
         }
         const copy=cloneDeep(temp)
         //@ts-ignore
         editClos.value.push(copy);
        }else {
      let temp = {
        dataIndex: value[i].FieldName,
        title: value[i].Unit
          ? value[i].ParamName + "(" + value[i].Unit + ")"
          : value[i].ParamName,
        width: 100,
        customRender: function (record:any) {
          const curCols = record.column
          const cueRecord = record.record
          if (curCols.dataIndex == 'EditTargetVal' ||
            curCols.dataIndex == 'EditFunTargetVal' ||
            curCols.dataIndex == 'TargetVal' ||
            curCols.dataIndex == 'ErrorLimit' ||
            curCols.dataIndex == 'Standant') {
            return (
              <a-input
                size="small"
                autofocus={true}
                v-inputFloat
                readonly={
                  cueRecord.Status > 1 &&
                  (curCols.Field != 'TargetVal' ||
                    curCols.Field != 'EditTargetVal')
                }
                v-model:value=
                {
                  cueRecord[curCols.dataIndex]
                }
              />
            )
          } else {
            return <a-input
              size="small"
              autofocus={true}
              onClick={() => {
                handleCellClick(cueRecord, curCols)
              }}
              readonly={
                cueRecord.Status > 1 &&
                (curCols.Field != 'TargetVal' ||
                  curCols.Field != 'EditTargetVal')
              }
              v-model:value=
              {
                cueRecord[curCols.dataIndex]
              }
            />
          }
        }


      };
      const copy=cloneDeep(temp)
         //@ts-ignore
         editClos.value.push(copy);
    }
  } 
  
})

const getCommonSelectOption=function(value:any){ 
  for(let i=0;i<value.length;i++){
    return  <a-select-option   key={value[i].ItemId} label={value[i].ItemName}
                        value={value[i].ItemId.toString()}>{value[i].ItemName}
                        </a-select-option>
    }
  }
  
const handleInputSelect=function(item:any) {
      //此处强制更新视图
      if (item.ChildItemFields) {
        for (let i = 0; i < item.ChildItemFields.length; i++) {
          selectRow.value[item.ChildItemFields[i]] = ""
        }
      }
    }

 const  getSelectItems=function(item:funParamaStruct) {
      //通过限定字段限定选项的值

      const target = funParam.value.filter((list:any) => {
        //@ts-ignore
        return list.FieldName == item.Field
      })
      if (target.length > 0) {
        if (selectRow.value != null && typeof selectRow.value[item.ItemFilterField] != "undefined" && selectRow.value[item.ItemFilterField] != "") {
          //this.form[item.FieldName] = "" //值改变的时候，清空当前选项
          //@ts-ignore
          return item.Option.filter((list) => {
            return list.FilterValue.indexOf(parseInt(selectRow.value[item.ItemFilterField])) != -1 || list.FilterValue == null
          })
        } else {
          //@ts-ignore
          return item.Option
        }
      } else {
        return []
      }
    }

const getDelBtn = function (record:any) {
  return (
    <a-button type="text"
      title="删除" size="small" style="height: 24px; color: dodgerblue;font-weight: bold;"
      onClick={() => {
        handleDelMatDatas(record)
      }}
    >
      <i class="icon icon-trash"></i>
    </a-button>
  )
}

const _getMatOption = function () {
  return MaterialFunOption.value.map((list:any) => {
    return (
      <a-select-option key={list.Key}
        value={list.Key} >{list.Label}
      </a-select-option>
    );
  });
}

const _getExpressionOption = function () {
  return ExpressionNameOption.value.map((list:any) => {
    return (
      <a-select-option key={list.Key}
        value={list.Key} >{list.Label}
      </a-select-option>
    );
  });
}

const handleSelectChange = function (field:string, row:any) {
  let label = "";
  if (field == "ExpressionItemId") {
    let targetVal = props.ExpressionOption.filter((item) => {
      return item.key == row.ExpressionItemId;
    });
    if (targetVal.length > 0) {
      label = targetVal[0].label;
    }
  }
  //this.$set(row, "ExpressionItemName", label);
}
const handleClear = function (field:string, row:any) {
  // this.$set(row, "ExpressionItemName", "");
  // this.$set(row, "ExpressionItemId", "");
}
const handleCellClick = function (record:any, cloumn:any) {
  //单元格点击事件
  selectRow.value = record;

  if (
    cloumn.dataIndex == "EditMatName" ||
    cloumn.dataIndex == "RecipeMatName" ||
    cloumn.dataIndex == "DisplayMaterialName"
  ) {
    //如果是物料选择列，则弹出选择物料界面
    showMatreial.value = true;
  }
}

const handleAddMatDatas = function () {
  //新增数据
  let temp = cloneDeep(dataStruct)
  temp.index = GuidID();
  temp.ParantID=ParantID.value
  //@ts-ignore
  materialDatas.value.push(temp);
  selectRow.value = materialDatas.value[materialDatas.value.length - 1]
}
const handleDelMatDatas = function (row:any) {
  //删除物料信息
  for (let i = 0; i < materialDatas.value.length; i++) {
    //@ts-ignore
    if (materialDatas.value[i].index == row.index) {
      materialDatas.value.splice(i, 1);
      break;
    }
  }
}


const handleMatfirm = function () {
  if (materialData.value == null && materialCheckData.value.length == 0) {
    Modal.warning({
      title: "警告",
      content: "请先选择物料!"
    })
    return;
  }

  if (materialCheckData.value.length == 0) {
    selectRow.value.EditMatName = materialData.value.MaterialCode
      ? materialData.value.MaterialCode
      : ""; //物料编码
    selectRow.value.DisplayMaterialName = materialData.value.MaterialName
      ? materialData.value.MaterialName
      : ""; //物料名称
    selectRow.value.RecipeMatName = materialData.value.TechMaterialName
      ? materialData.value.TechMaterialName
      : ""; //技术部专用名称
    if (materialData.value.MatStandant) {
      //ERPbom里面过来的标准用量
      selectRow.value.EditTargetVal = materialData.value.MatStandant
    }
    if (materialData.value.MatErrorLimit) {
      selectRow.value.ErrorLimit = materialData.value.MatErrorLimit
    }

  } else {
    //ERPbom允许多选
    for (let i = 0; i < materialDatas.value.length; i++) {
      //@ts-ignore
      if (selectRow.value.index == materialDatas.value[i].index) {
        materialDatas.value.splice(i, 1)
        break
      }
    }
    for (let j = 0; j < materialCheckData.value.length; j++) {
      let temp = cloneDeep(dataStruct)
      $.extend(true, temp, dataStruct)
      temp.index = GuidID()
      temp.EditMatName = materialCheckData.value[j].MaterialCode
      //物料编码
      temp.DisplayMaterialName = materialCheckData.value[j].MaterialName
      //物料名称
      temp.RecipeMatName = materialCheckData.value[j].TechMaterialName
      //技术部专用名称
      temp.EditTargetVal = materialCheckData.value[j].MatStandant
      temp.ErrorLimit = materialCheckData.value[j].MatErrorLimit
      let copy = cloneDeep(temp)
     //@ts-ignore
      materialDatas.value.push(copy)
    }


  }
  showMatreial.value = false;

}
const handleMatClose = function () {
  //关闭材料面板
  showMatreial.value = false;
  // this.$nextTick(() => {
  //   this.createValidateToolTip(this.$el);
  // });
}

const handleConfirm = function () {
  //确认修改数据
  form.ParantID = ParantID.value; //提交数据的时候，赋值parentID

  for (let i = 0; i < materialDatas.value.length; i++) {

    materialDatas.value[i].ParantID = ParantID.value;
    if (

      typeof materialDatas.value[i].EditTargetVal != 'undefined' &&

      typeof materialDatas.value[i].RealValue != 'undefined'
    ) {
      if (
 
        materialDatas.value[i].RealValue -
        materialDatas.value[i].EditTargetVal >
        Number.EPSILON
      ) {
        Modal.warning({
          title: "警告",
          content: "行" + (i + 1) + "目标量不能小于实际量!"
        })

        materialDatas.value[i].EditTargetVal =
   
          materialDatas.value[i].RealValue;
        return;
      }
    }
    if (

      typeof materialDatas.value[i].TargetVal != 'undefined' &&
 
      materialDatas.value[i].RealValue
    ) {
      if (

        materialDatas.value[i].RealValue - materialDatas.value[i].TargetVal >
        Number.EPSILON
      ) {
        materialDatas.value[i].TargetVal = materialDatas.value[i].RealValue;
        Modal.warning({
          title: "警告",
          content: "行" + (i + 1) + "目标量不能小于实际量!"
        })
        return;
      }
    }
    if (props.isHaveMaterial) {
      if (
        typeof materialDatas.value[i].EditMatName == "undefined" ||
        !materialDatas.value[i].EditMatName
      ) {
        Modal.warning({
          title: "警告",
          content: "行" + (i + 1) + "物料名称不能为空!"
        })

      }
    }
    let small =
      accSub(materialDatas.value[i].ErrorLimit, 0.000001) < 0.0001;
    if (
      typeof materialDatas.value[i].ErrorLimit == "undefined" ||
      !materialDatas.value[i].ErrorLimit ||
      small
    ) {
      materialDatas.value[i].ErrorLimit = props.errorLimitDefaultVal;
    }

    materialDatas.value[i].TargetVal =
      typeof materialDatas.value[i].EditTargetVal == "undefined"
        ? 0
        : materialDatas.value[i].EditTargetVal;
  }

  if (props.matLimitOption.length > 0) {
    //如果物料限制长度大于零，则需要对物料加料量进行检查，只用于改单情况下
    let bRet = true
    for (let i = 0; i < materialDatas.value.length; i++) {
      materialDatas.value[i].IsAdjust = true //调整状态下，将每一步骤都打上调整标志
      if (checkLimitMatWeight(materialDatas.value[i]) == false) {
        bRet = false
        break
      }
    }
    if (!bRet) {
      return
    }
  }

  checkIsMatChange()

  const sendData = {
    showCols: JSON.parse(JSON.stringify(getShowData())),
    EditCols: JSON.parse(JSON.stringify(materialDatas.value)),
  };
  const propertyData = {
    data: sendData,
    type: "Table", //标准工艺
    targetId: cellID.value,
  };
  events.emit("porpertyChange", propertyData);
  emits("closeParamForm", 1);
}

const checkIsMatChange = function () {
  if (localOriginData.value.length == 0) {
    return //如果是新增，则不处理
  }
  for (let i = 0; i < localOriginData.value.length; i++) {
    let targetItem = materialDatas.value.filter((item:any) => {
      return item.keyWord == localOriginData.value[i].DetailOrderKey
    })
    if (targetItem.length > 0) {
      //如果关键字一致，但是物料名称不一致，则需要清空关键字
      if (targetItem[0].EditMatName != localOriginData.value[i].EditMatName) {
        targetItem[0].DetailOrderKey = null
        targetItem[0].keyWord = null
      }
    }
  }
}
const checkLimitMatWeight = function (data:materialItemStruct) {
  //判断当前物料的上限有没有超
  let MaterialCode = data.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 (var i in cells) {
      if (typeof cells[i].cellType == "undefined") {
        continue;
      }
      if (cells[i].IsAdjust) {
        if (cells[i].cellType == "Table") {
          if (cells[i].DetailOrderKey != DetailOrderKey.value) {
            //如果不是当前投料组，才需要计算，否则计算没有意义
            if (typeof cells[i].EditCols != "undefined") {
              for (let j = 0; j < cells[i].EditCols.length; j++) {
                if (cells[i].EditCols[j].EditMatName == MaterialCode && cells[i].EditCols[j].DetailOrderKey != data.keyWord) {
                  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 (typeof cells[i].EditTargetVal != 'undefined') {
              if (cells[i].EditMatName == MaterialCode) {
                totalWeight = accAdd(
                  totalWeight,
                  parseFloat(typeof cells[i].EditTargetVal == 'undefined' || cells[i].EditTargetVal == "" ? 0 : cells[i].EditTargetVal)
                );
              }

            }
          }
        }
      }
    }
    if (accAdd(totalWeight, data.EditTargetVal) > highrLimit) {
      let currentlimit = totalWeight == 0 ? highrLimit : accSub(highrLimit, totalWeight)
      Modal.warning({
        title: "警告",
        content: "物料" + MaterialCode + "已超限，当前最大物料加入量为" + currentlimit
      })

      bRet = false
    }
  }
  return bRet
}


const getShowData = function () {
  //获取需要显示的列信息
  let tempArray = [];
  let tempItem = [
    {
      name: "",
      field: "DetailOrderKey",
    },
  ];
  for (let i = 0; i < showFunParam.value.length; i++) {
    if (showFunParam.value[i].FieldName == "ParantID") {
      continue;
    }
    if (showFunParam.value[i].FieldName == "ExpressionItemId") {
      //将实际需要显示的值替换成公式实际内容
      showFunParam.value[i].FieldName = "ExpressionItemName";
    }
    let temp = {
      name: showFunParam.value[i].Unit
        ? showFunParam.value[i].ParamName +
        "(" +
        showFunParam.value[i].Unit +
        ")"
        : showFunParam.value[i].ParamName,
      field: showFunParam.value[i].FieldName,
    };
    let copy = cloneDeep(temp)
    tempItem.push(copy);
  }
  tempArray.push(tempItem); //显示表格头信息

  for (let j = 0; j < materialDatas.value.length; j++) {
    let item = {};
    for (let k = 0; k < showFunParam.value.length; k++) {
      if (showFunParam.value[k].FieldName == "ParantID") {
        continue;
      }
      if (showFunParam.value[k].FieldName == "ExpressionItemName") {
        //@ts-ignore
        showFunParam.value[k].ExpressionItemName = getExpressName(materialDatas.value[j].ExpressionItemId)
      } else if (typeof showFunParam.value[k].SelectItems != "undefined" && showFunParam.value[k].SelectItems.length > 0) {
            //@ts-ignore
            item[showFunParam.value[k].FieldName] =getShowName(materialDatas.value[j][showFunParam.value[k].FieldName], showFunParam.value[k].SelectItems)
          }
      else {
        //@ts-ignore
        item[showFunParam.value[k].FieldName] = typeof materialDatas.value[j][showFunParam.value[k].FieldName] !=
          "undefined" //需要注意，工艺码为空的情况
          ? materialDatas.value[j][showFunParam.value[k].FieldName]
          : _getOriginShowData(
            materialDatas.value[j],
            showFunParam.value[k].FieldName
          )
      }
    }
    tempArray.push(item);
  }
  return tempArray;
}

const getShowName=function(value:number, Option:any) {
      let label = ""
      for (let i = 0; i < Option.length; i++) {
        if (Option[i].ItemId.toString() == value) {
          label = Option[i].ItemName
          break
        }
      }
      return label
    }
const getExpressName = function (key:string) {
  let label = "";
  for (let i = 0; i < props.ExpressionOption.length; i++) {
    if (props.ExpressionOption[i].key == key) {
      label = props.ExpressionOption[i].label;
      break;
    }
  }
  return label;
}
const _getOriginShowData = function (data:any, Field:string) {
  //获取显示数据
  let showValue = "";
  for (let i in showColDatas.value) {
    if (showColDatas.value[i].DetailOrderKey) {
      if (showColDatas.value[i].DetailOrderKey == data.DetailOrderKey) {
        showValue = showColDatas.value[i][Field];
        break;
      }
    }
  }
  return showValue;
}
const handleReset = function () {
  //初始化的时候，将页面初始化成初始结构
  //如果初始数组不为空，则重置成初始数组
  $.extend(true, form, dataStruct);
  form.ParantID = props.formData.RecipeStyle;
  materialDatas.value = props.formData.EditCols;

}

const getFunNameByFunID = function (value:number) {
  var name = "";
  if (value == -1) {
    return "物料计量";
  }
  for (var i = 0; i < props.funOption.length; i++) {
    if (props.funOption[i].FuncId == value) {
      name = props.funOption[i].FunctionName2;
      break;
    }
  }
  return name;
}

const handleMatDbClick = function (row:any, dataIndex:number, event:any) {
  //双击材料行
  selectRow.value.EditMatName = row.MaterialCode ? row.MaterialCode : "";
  selectRow.value.DisplayMaterialName = row.MaterialName
    ? row.MaterialName
    : "";
  selectRow.value.RecipeMatName = row.TechMaterialName
    ? row.TechMaterialName
    : "";
  if (row.MatStandant) {
    //ERPbom里面过来的标准用量
    selectRow.value.EditTargetVal = row.MatStandant
  }
  if (row.MatErrorLimit) {
    selectRow.value.ErrorLimit = row.MatErrorLimit
  }
  showMatreial.value = false;
}

const getFunParam = function (functID:number, parentData?:any) {
  funParam.value = [];
  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;
      if (typeof parentData == "undefined") {
        formatDataStruct(funParam.value);
      } else {
        formatDataStruct(funParam.value, parentData);
      }
    })
    .catch((data:any) => {
      //提交失败的时候，直接抛出后台报错
      //self.$message(data.Message);
    });
}

const formatDataStruct = function (data:any, parentData?:any) {
  //根据接口，初始化form结构
  if (data.length < 1) {
    //如果工艺参数没有设置
    dataStruct = {};
    $.extend(true, form, dataStruct);
    return;
  }
  for (var i = 0; i < data.length; i++) {
    dataStruct[data[i].FieldName] = "";
    // if (this.IsMaterial == true) {
    dataStruct.DisplayMaterialName =
      typeof props.formData.DisplayMaterialName == 'undefined'
        ? ""
        : props.formData.DisplayMaterialName;
    dataStruct.EditMatName =
      typeof props.formData.EditMatName == 'undefined'
        ? ""
        : props.formData.EditMatName;
    dataStruct.RecipeMatName =
      typeof props.formData.RecipeMatName == 'undefined'
        ? ""
        : props.formData.RecipeMatName;
  }
  // }
  $.extend(true, form, dataStruct);
  //form.ParantID = props.formData.RecipeStyle;
}



onBeforeMount(() => {
  initFormVal()
})



</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;
}

.box-card .ant-form-item {
  border-left: 0px !important;
}
</style>
<style>
#refTableMatGroup .ant-select.ant-select-sm.ant-select-single.ant-select-show-arrow {
  width: 100%;
}
</style>
