<template>
  <create-view
    :loading="loading"
    :body-style="{ height: '100%' }"
    :width="width"
  >
    <flexbox direction="column" align="stretch" class="crm-create-container">
      <flexbox class="crm-create-header">
        <div style="flex: 1; font-size: 17px; color: #333">{{ title }}</div>
        <img
          class="close"
          src="@/assets/img/task_close.png"
          @click="hidenView"
        />
      </flexbox>
      <div class="crm-create-flex">
        <create-sections title="基本信息">
          <flexbox direction="column" align="stretch">
            <div class="crm-create-body">
              <el-form
                ref="crmForm"
                :model="crmForm"
                label-position="top"
                class="crm-create-box"
              >
              <!-- :prop="'crmFields.' + index + '.value'" -->
                <el-form-item
                  v-for="(item, index) in crmForm.crmFields"
                  :key="item.key"
                  :prop="'crmFields.' + index + '.value'"
                  :class="{
                    'crm-create-block-item': item.showblock,
                    'crm-create-item': !item.showblock,
                  }"
                  :rules="crmRules[item.key]"
                  :style="{
                    'padding-left': getPaddingLeft(item, index),
                    'padding-right': getPaddingRight(item, index),
                  }"
                >
                  <div slot="label" style="display: inline-block">
                    <div
                      style="
                        margin: 5px 0;
                        font-size: 12px;
                        word-wrap: break-word;
                        word-break: break-all;
                      "
                    >
                      {{ item.data.name }} 
                      <span style="color: #999">
                        {{
                          item.data.inputTips
                            ? "（" + item.data.inputTips + "）"
                            : ""
                        }}
                      </span>
                    </div>
                  </div>
                  <component
                    :is="item.data.formType | typeToComponentName"
                    :value="item.value"
                    :index="index"
                    :item="item"
                    :relation="item.relation"
                    :radio="false"
                    :disabled="item.disabled"
                    @value-change="fieldValueChange"
                  />
                </el-form-item>
              </el-form>
            </div>
          </flexbox>
        </create-sections>
      </div>
<!-- 
      <DialogTable
        ref="formDialog"
        :logMessage="{}"
        v-if="crmType == 'dicts' && action.type != 'update'"
      ></DialogTable> -->

      <div class="handle-bar">
        <el-button class="handle-button" @click.native="hidenView"
          >取消</el-button
        >
        <el-button
          class="handle-button"
          type="primary"
          :disabled="saveDisabled"
          @click.native="saveField(false)"
          >保存</el-button
        >
      </div>
    </flexbox>
  </create-view>
</template>
<script type="text/javascript">
import crmTypeModel from "@/views/ux/model/crmTypeModel";
import CreateView from "@/components/CreateView";
import CreateSections from "@/components/CreateSections";
import DialogTable from "../dict/components/DialogTable";
import { crmLeadsSave, crmLeadsRead, crmLeadsUpdate } from "@/api/ux/clue";
import {
  crmDictsSave,
  crmDictsRead,
  crmDictsUpdate,
  crmDictsItemDetailRead,
  crmDictsItemIndex,
  crmDictsItemAdd,
  crmDictsItemUpdate,
} from "@/api/dict/dict";
import {
  crmTransactionSave,
  crmTransactionRead,
  crmTransactionUpdate,
} from "@/api/transaction/transaction";
import {
  crmStrategySave,
  crmStrategyRead,
  crmStrategyUpdate,
} from "@/api/strategy/strategy";
import { crmRuleSave, crmRuleRead, crmRuleUpdate } from "@/api/rule/rule";
import {
  crmStrategyRulesSave,
  crmStrategyRulesRead,
  crmStrategyRulesUpdate,
} from "@/api/strategyRules/strategyRules";
import {
  crmVerificationSave,
  crmVerificationRead,
  crmVerificationUpdate,
} from "@/api/verification/verification";
import { crmStageSave, crmStageRead, crmStageUpdate } from "@/api/stage/stage";
import {
  crmCustomerSave,
  crmCustomerRead,
  crmCustomerUpdate,
} from "@/api/customer/customer";
import {
  crmSlgItemSave,
  crmSlgItemRead,
  crmSlgItemUpdate,
} from "@/api/slgItem/slgItem";
//add-fdw-引入bom-保存、读取、更新
import { crmBomSave, crmBomRead, crmBomUpdate } from "@/api/bom/bom";
//add-fdw-引主uomgroup-保存、读取、更新
import {
  crmUomGroupSave,
  crmUomGroupRead,
  crmUomGroupUpdate,
} from "@/api/uomGroup/uomGroup";
import { crmUomSave, crmUomRead, crmUomUpdate } from "@/api/uom/uom";
import {
  crmInterfaceCalendarSave,
  crmInterfaceCalendarRead,
  crmInterfaceCalendarUpdate,
} from "@/api/interfaceCalendar/interfaceCalendar";
import {
  crmVerificationStagesSave,
  crmVerificationStagesRead,
  crmVerificationStagesUpdate,
} from "@/api/verificationStages/verificationStages";
import { crmAreaSave, crmAreaRead, crmAreaUpdate } from "@/api/area/area"; // 区域
import {
  crmAreaItemSave,
  crmAreaItemRead,
  crmAreaItemUpdate,
} from "@/api/areaItem/areaItem"; // 区域-物品
import {
  crmCurrencySave,
  crmCurrencyRead,
  crmCurrencyUpdate,
} from "@/api/currency/currency"; // 货币
import {
  crmCurrencyExchangeSave,
  crmCurrencyExchangeRead,
  crmCurrencyExchangeUpdate,
} from "@/api/currencyExchange/currencyExchange"; // 货币换算
import {
  crmCustomerBomSave,
  crmCustomerBomRead,
  crmCustomerBomUpdate,
} from "@/api/customerBom/customerBom"; // 客户物品产品结构
import {
  crmCustomerItemSave,
  crmCustomerItemRead,
  crmCustomerItemUpdate,
} from "@/api/customerItem/customerItem"; // 客户物品
import {
  crmEqptTypeSave,
  crmEqptTypeRead,
  crmEqptTypeUpdate,
} from "@/api/eqptType/eqptType"; // 器具类型
import {
  crmEqptTypeItemSave,
  crmEqptTypeItemRead,
  crmEqptTypeItemUpdate,
} from "@/api/eqptTypeItem/eqptTypeItem"; // 器具类型-物品
import { crmItemSave, crmItemRead, crmItemUpdate } from "@/api/item/item"; // 物品
import {
  crmItemTransTypeInventoryRouteSave,
  crmItemTransTypeInventoryRouteRead,
  crmItemTransTypeInventoryRouteUpdate,
} from "@/api/itemTransTypeInventoryRoute/itemTransTypeInventoryRoute"; // 物品-事务类型-物流路线分配
import {
  crmItemTransTypeOpStrategySave,
  crmItemTransTypeOpStrategyRead,
  crmItemTransTypeOpStrategyUpdate,
} from "@/api/itemTransTypeOpStrategy/itemTransTypeOpStrategy"; // 物品-事务类型-工序-策略分配
import { crmLocSave, crmLocRead, crmLocUpdate } from "@/api/loc/loc"; // 库位
import {
  crmMachineSave,
  crmMachineRead,
  crmMachineUpdate,
} from "@/api/machine/machine"; // 机器
import { crmParamSave, crmParamRead, crmParamUpdate } from "@/api/param/param"; // 参数
import { crmPortSave, crmPortRead, crmPortUpdate } from "@/api/port/port"; // 收货口
import {
  crmProdLineSave,
  crmProdLineRead,
  crmProdLineUpdate,
} from "@/api/prodLine/prodLine"; // 生产线
import {
  crmProdLineItemSave,
  crmProdLineItemRead,
  crmProdLineItemUpdate,
} from "@/api/prodLineItem/prodLineItem"; // 生产线-物品
import {
  crmProjectSave,
  crmProjectRead,
  crmProjectUpdate,
} from "@/api/project/project"; // 项目
import { crmShiftSave, crmShiftRead, crmShiftUpdate } from "@/api/shift/shift"; // 班次
import { crmSlgSave, crmSlgRead, crmSlgUpdate } from "@/api/slg/slg"; // 库位组
import {
  crmSupplierSave,
  crmSupplierRead,
  crmSupplierUpdate,
} from "@/api/supplier/supplier"; // 供应商
import {
  crmSupplierItemSave,
  crmSupplierItemRead,
  crmSupplierItemUpdate,
} from "@/api/supplierItem/supplierItem"; // 供应商物品
import { crmTeamSave, crmTeamRead, crmTeamUpdate } from "@/api/team/team"; // 班组
import {
  crmUomConversionSave,
  crmUomConversionRead,
  crmUomConversionUpdate,
} from "@/api/uomConversion/uomConversion"; // 计量单位转换
import { crmWlgSave, crmWlgRead, crmWlgUpdate } from "@/api/wlg/wlg"; // 工作组
import {
  crmWlgItemSave,
  crmWlgItemRead,
  crmWlgItemUpdate,
} from "@/api/wlgItem/wlgItem"; // 工作组-物品
import {
  crmWorkCalendarSave,
  crmWorkCalendarRead,
  crmWorkCalendarUpdate,
} from "@/api/workCalendar/workCalendar"; // 工作日历
import {
  crmWorkCenterSave,
  crmWorkCenterRead,
  crmWorkCenterUpdate,
} from "@/api/workCenter/workCenter"; // 工作中心
import {
  crmInventoryRouteSave,
  crmInventoryRouteRead,
  crmInventoryRouteUpdate,
  crmInventoryRouteDetailRead,
  crmInventoryRouteDetailIndex,
  crmInventoryRouteDetailAdd,
  crmInventoryRouteDetailUpdate,
} from "@/api/inventoryRoute/inventoryRoute"; //物流路线
import {
  crmPurchasePriceSheetSave,
  crmPurchasePriceSheetRead,
  crmPurchasePriceSheetUpdate,
  crmPurchasePriceDetailRead,
  crmPurchasePriceDetailIndex,
  crmPurchasePriceDetailAdd,
  crmPurchasePriceDetailUpdate,
} from "@/api/purchasePriceSheet/purchasePriceSheet"; //采购价格单
import {
  crmRouteSave,
  crmRouteRead,
  crmRouteUpdate,
  crmRouteDetailRead,
  crmRouteDetailIndex,
  crmRouteDetailAdd,
  crmRouteDetailUpdate,
} from "@/api/route/route"; //工艺路线

import {
  crmSalePriceSheetSave,
  crmSalePriceSheetRead,
  crmSalePriceSheetUpdate,
  crmSalePriceDetailRead,
  crmSalePriceDetailIndex,
  crmSalePriceDetailAdd,
  crmSalePriceDetailUpdate,
} from "@/api/salePriceSheet/salePriceSheet"; //销售价格单

import {
  crmStdCostPriceSheetSave,
  crmStdCostPriceSheetRead,
  crmStdCostPriceSheetUpdate,
  crmStdCostPriceDetailRead,
  crmStdCostPriceDetailIndex,
  crmStdCostPriceDetailAdd,
  crmStdCostPriceDetailUpdate,
} from "@/api/stdCostPriceSheet/stdCostPriceSheet"; //标准成本价格单

import { crmOrgRead } from "@/api/org/org";
//import {crmUomRead} from '@/api/uom/uom'
//新增业务的创建、修改引入的两个json文件
import data from "../../../../static/createField";
import dataupdate from "../../../../static/updateField";
import crmtypes from "../../../../static/crmTypes";

import {
  regexIsInt,
  regexIsNumber,
  regexIsCRMNumber,
  regexIsCRMNumber2,
  regexIsCRMNumber4,
  regexIsCRMMoneyNumber,
  regexIsCRMMobile,
  regexIsCRMEmail,
  regexIsCRMRate,
  objDeepCopy,
} from "@/utils";

import { isArray } from "@/utils/types";

import Lockr from "lockr";

import {
  XhInput,
  XhTextarea,
  XhSelect,
  XhSwitch,
  XhMultipleSelect,
  XhDate,
  XhDateTime,
  XhUserCell,
  XhStructureCell,
  XhFiles,
  CrmRelativeCell,
  XhProuctCate,
  XhProduct,
  XhBusinessStatus,
  XhCustomerAddress,
  XhReceivablesPlan, // 回款计划期数
} from "@/components/CreateCom";

export default {
  name: "CrmCreateView", // 所有新建效果的view
  components: {
    CreateView,
    CreateSections,
    XhInput,
    XhTextarea,
    XhSelect,
    XhSwitch,
    XhMultipleSelect,
    XhDate,
    XhDateTime,
    XhUserCell,
    XhStructureCell,
    XhFiles,
    CrmRelativeCell,
    XhProuctCate,
    XhProduct,
    XhBusinessStatus,
    XhCustomerAddress,
    XhReceivablesPlan,
    DialogTable, //子表表格组件
  },
  filters: {
    /** 根据type 找到组件 */
    typeToComponentName(formType) {
      // if (
      //   formType == "text" ||
      //   formType == "number" ||
      //   formType == "floatnumber" ||
      //   formType == "mobile" ||
      //   formType == "email"
      // ) 
      
      if(formType == "text" || 
         formType== "int" || 
         formType == "number" ||
         formType == "number2" || 
         formType == "number4" ||  
         formType == "moneynumber" || 
         formType == "mobile" ||  
         formType == "email" ||
         formType == "rate" )
      {
        return "XhInput";
      } else if (formType == "textarea") {
        return "XhTextarea";
      } else if (formType == "select" || formType == "business_status") {
        return "XhSelect";
      } else if (formType == "switch") {
        return "XhSwitch";
      } else if (formType == "checkbox") {
        return "XhMultipleSelect";
      } else if (formType == "date") {
        return "XhDate";
      } else if (formType == "datetime") {
        return "XhDateTime";
      } else if (formType == "user") {
        return "XhUserCell";
      } else if (formType == "structure") {
        return "XhStructureCell";
      } else if (formType == "file") {
        return "XhFiles";
      } else if (
        //add-fdw-自定义弹出框
        formType == "contacts" ||
        formType == "customer" ||
        formType == "contract" ||
        formType == "business" ||
        formType == "strategy" ||
        formType == "rule" ||
        formType == "route" ||
        formType == "org" ||
        formType == "slg" ||
        formType == "item" ||
        formType == "bom" ||
        formType == "uom" ||
        formType == "uomGroup" ||
        formType == "verification" ||
        formType == "stage" ||
        formType == "area" ||
        formType == "areaItem" ||
        formType == "currency" ||
        formType == "currencyExchange" ||
        formType == "customerBom" ||
        formType == "customerItem" ||
        formType == "eqptType" ||
        formType == "eqptTypeItem" ||
        formType == "itemTransTypeInventoryRoute" ||
        formType == "itemTransTypeOpStrategy" ||
        formType == "loc" ||
        formType == "machine" ||
        formType == "param" ||
        formType == "port" ||
        formType == "prodLine" ||
        formType == "prodLineItem" ||
        formType == "project" ||
        formType == "shift" ||
        formType == "slg" ||
        formType == "supplier" ||
        formType == "supplierItem" ||
        formType == "team" ||
        formType == "uomConversion" ||
        formType == "wlg" ||
        formType == "wlgItem" ||
        formType == "workCalendar" ||
        formType == "workCenter" ||
        formType == "inventoryRoute" ||
        formType == "purchaseUomConversion" ||
        formType == "stockUomConversion" ||
        formType == "productionUomConversion" ||
        formType == "sellUomConversion" ||
        formType == "allocation"
      ) {
        return "CrmRelativeCell";
      } else if (formType == "category") {
        // 产品类别
        return "XhProuctCate";
      } else if (formType == "business_type") {
        // 商机类别
        return "XhBusinessStatus";
      } else if (formType == "product") {
        return "XhProduct";
      } else if (formType == "map_address") {
        return "XhCustomerAddress";
      } else if (formType == "receivables_plan") {
        return "XhReceivablesPlan";
      }
    },
  },
  props: {
    // CRM类型
    crmType: {
      type: String,
      default: "",
    },
    action: {
      type: Object,//updata:更新 create:新建 detail:详细信息
      default: () => {
        return {
          type: "save",
          id: "",
          subid: "",
          data: {}, // 编辑所需信息
        };
      },
    },
    width: {
      type: String,
      default: "700px",
    },
    formTitle:''
  },
  data() {
    return {
      // 标题展示名称
      title: "",
      loading: false,
      saveAndCreate: false, // 保存并新建
      // 自定义字段验证规则
      crmRules: {},
      // 自定义字段信息表单
      crmForm: {
        crmFields: [],
      },
      // 审批信息
      examineInfo: {},
      formLabelWidth: "80px",
      limitNum: 1,
      dialogImageUrl: "",
      //表单信息
      crmData: {},
      //子表信息
      subtableData: [],
      crmTypes:{},
      saveDisabled:false
    };
  },
  computed: {
    
  },
  watch: {
    crmType: function (value) {
      this.title = this.getTitle();
      this.crmRules = {};
      this.crmForm = {
        crmFields: [],
      };
      this.examineInfo = {};
      this.getField();
    },
  },
  mounted() {
    // 获取title展示名称
    document.body.appendChild(this.$el);
    this.crmTypes=crmtypes;
    if(this.action.type == "detail")
    {
      this.saveDisabled=true;
    }
    else {
      this.saveDisabled=false;
    }
    this.title = this.getTitle();
    this.getField();

    // 注册子表组件传来的数据方法
    this.$bus.$on("updateData", (content) => {
      this.subtableData = content;
      console.log(JSON.stringify(this.subtableData));
    });
  },
  destroyed() {
    // remove DOM node after destroy
    if (this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el);
    }
    this.crmData = {};
    // this.bus.$off('updateData',(content)=>{
    // });
  },
  methods: {
    // 审批信息值更新
    examineValueChange(data) {
      this.examineInfo = data;
    },
    // 字段的值更新
    fieldValueChange(data) {
      var item = this.crmForm.crmFields[data.index];
      item.value = data.value;

      // 无事件的处理 后期可换成input实现
      if (
        item.data.formType == "user" ||
        item.data.formType == "structure" ||
        item.data.formType == "file" ||
        item.data.formType == "category" ||
        item.data.formType == "customer" ||
        item.data.formType == "business" ||
        item.data.formType == "contract" ||
        item.data.formType == "strategy" ||
        item.data.formType == "rule" ||
        item.data.formType == "org" ||
        item.data.formType == "slg" ||
        item.data.formType == "item" ||
        item.data.formType == "bom" ||
        item.data.formType == "uom" ||
        item.data.formType == "uomGroup" ||
        item.data.formType == "verification" ||
        item.data.formType == "stage" ||
        item.data.formType == "area" ||
        item.data.formType == "areaItem" ||
        item.data.formType == "currency" ||
        item.data.formType == "currencyExchange" ||
        item.data.formType == "customerBom" ||
        item.data.formType == "customerItem" ||
        item.data.formType == "eqptType" ||
        item.data.formType == "eqptTypeItem" ||
        item.data.formType == "itemTransTypeInventoryRoute" ||
        item.data.formType == "itemTransTypeOpStrategy" ||
        item.data.formType == "loc" ||
        item.data.formType == "machine" ||
        item.data.formType == "param" ||
        item.data.formType == "port" ||
        item.data.formType == "prodLine" ||
        item.data.formType == "prodLineItem" ||
        item.data.formType == "project" ||
        item.data.formType == "shift" ||
        item.data.formType == "slg" ||
        item.data.formType == "supplier" ||
        item.data.formType == "supplierItem" ||
        item.data.formType == "team" ||
        item.data.formType == "uomConversion" ||
        item.data.formType == "wlg" ||
        item.data.formType == "wlgItem" ||
        item.data.formType == "workCalendar" ||
        item.data.formType == "workCenter"|| 
        item.data.formType == "route"
      ) {
        this.$refs.crmForm.validateField("crmFields." + data.index + ".value");
      }
    },

    getField() {
      this.loading = true;
       // 进行编辑操作
      if (this.action.type == "update" || this.action.type == "detail") {
        this.getUpdateField();
      } else {
        console.log("----- 添加 -----");
        const filedList = data[this.crmType].data;
        this.getcrmRulesAndModel(filedList);
      }
      this.loading = false;
    },

    getUpdateField() {
      this.loading = true;
      const filedListEdit = dataupdate[this.crmType].data;
      // 获取自定义字段的更新时间
      var params = {
        label: crmTypeModel[this.crmType],
      };

      params.id = this.action.id;
      params.subid = this.action.subid; //子表Id

      //1.查询要编辑表的详细信息
      let crmRequest = this.getReadRequest();
      crmRequest(params.id, params.subid)
        .then((res) => {
          this.crmData = res;
          console.log(JSON.stringify(res));
          //2.遍历UpdateJson中的属性
          filedListEdit.map((item) => {
            //3.遍历从接口获取的返回值‘res’的属性
            Object.keys(res).forEach((key) => {
              if (key == item.fieldName) {
                //3.1如果字段的值来自关联表
                if (key.endsWith("ID") && item.formType != "text") {
                  //3.1.1获取关联表的请求
                  let relationReadRequest = this.getReadRequest(item.formType);
                  if (
                    relationReadRequest == undefined ||
                    relationReadRequest == ""
                  ) {
                    console.log(
                      "------ update没有找到 " +
                        item.formType +
                        " 的 crmXXXXRead -----"
                    );
                  } else {
                    relationReadRequest(res[key]).then((resRelation) => {
                      let _json = {};
                      _json["Id"] = res[key];
                      _json[key] = res[key];

                      if (key === "OrgID") {
                        _json["branchName"] = resRelation.name;
                      }
                      else
                      { 
                        _json["Code"] = resRelation.Code;
                        _json["Name"] = resRelation.Name;
                      }
                  
                      var _array = [_json];
                      item.value = _array;
                    }) .catch((error) => {
                      this.loading = false;
                    });;
                  }
                }
                //3.2 直接
                else {
                  item.value = res[key];
                }
              }
              this.loading = false;
            });
          });
          //4.根据filedListEdit渲染界面
          setTimeout((item) => {
            this.getcrmRulesAndModel(filedListEdit);
          }, 500);
        })
        .catch(() => {
          this.loading = false;
        });
    },

    // 根据自定义字段获取自定义字段规则及Model
    getcrmRulesAndModel(list) {
      console.log("----- 根据自定义字段获取自定义字段规则 -----");
      let showStyleIndex = -1;
      for (let index = 0; index < list.length; index++) {
        const item = list[index];
        showStyleIndex += 1;

        //规则
        this.crmRules[item.fieldName] = this.getItemRulesArrayFromItem(item);
        // let otherRules=this.getOtherRulesArrayFromItem(item,this.crmForm.crmFields);
        var params = {};
        if (this.action.type == "update") //编辑
        {
          params["value"] = item.value; //  
          params["disabled"]=item.disabled ||false; //控件是否可用
        } else if(this.action.type == "detail") //详细信息
        {
          params["value"] = item.value;
          params["disabled"]=true; //控件不可用
        }
        else //新增
         {
          //赋初始值
          if (item.formType === "text") {
            params["value"] = item.defaultValue || "";
           } else if(item.formType === "int" || 
            item.formType === "number"  || 
            item.formType === "number2" || 
            item.formType === "number4" || 
            item.formType === "moneynumber" || 
            item.formType === "rate")
          {
            //params["value"] =item.isNull===1? 0:null; 
            params["value"] =0; 
          } else if (item.formType === "switch") {
            params["value"] = true;
          } else if (item.formType === "datetime") {
            //params["value"] =item.isNull===1? this.getNowDate():null; 
            params["value"] =this.getNowDate()
          }else {
            params["value"] = item.defaultValue;
          }
          params["disabled"]=false; //新增控件可用
        }
        params["key"] = item.fieldName;
        params["data"] = item;
        params["styleIndex"] = showStyleIndex;
        this.crmForm.crmFields.push(params);
      }
    },

    // 保存数据
    saveField(saveAndCreate, isDraft = false) {
      console.log("-------- 保存 --------");
      this.saveAndCreate = saveAndCreate;
      this.$refs.crmForm.validate((valid) => {
        if (valid) {
          //其他校验
          var otherValid=this.getCrmFormOtherValidate()
          if(otherValid)
          {
            var params = this.getSubmiteParams(this.crmForm.crmFields);
            //获取其他参数
            this.getOtherParams(params);
           
            console.log("params" + JSON.stringify(params));
            this.submiteParams(params);
          }
        } else {
          this.$message.error('表单校验未通过,请查看表单信息');
          return false;
        }
      });
    }, 
    //获取其他校验规则
    getCrmFormOtherValidate()
    {
      if(this.crmType==='strategyRules' ||
         this.crmType==='uom' ||
         this.crmType==='uomConversion'  
      )
      {
        var EffectiveTimeValue= this.crmForm.crmFields.find(item=>{return item.key==='EffectiveTime'}).value;
        var ExpireTimeValue= this.crmForm.crmFields.find(item=>{return item.key==='ExpireTime'}).value;

         if(EffectiveTimeValue >= ExpireTimeValue){
            this.$message.error('生效时间不能大于等于失效时间');
            return false;
         } 
      }
      else if( 
              this.crmType==='project' ||
              this.crmType==='workCalendar' ||
              this.crmType==='shift' ||
              this.crmType==='interfaceCalendar' ||
              this.crmType==='purchasePriceDetail' ||
              this.crmType == "salePriceDetail" ||
              this.crmType == "stdCostPriceDetail"   )
      {
        var BeginTimeValue= this.crmForm.crmFields.find(item=>{return item.key==='BeginTime'}).value;
        var EndTimeValue= this.crmForm.crmFields.find(item=>{return item.key==='EndTime'}).value;

         if(BeginTimeValue >= EndTimeValue){
            this.$message.error('开始时间不能大于等于结束时间');
            return false;
         } 
      }
      else if(this.crmType==='customerBom' ||  this.crmType==='bom' )
      {
         var ParentItemCodeValue= this.crmForm.crmFields.find(item=>{return item.key==='ParentItemID'}).value;
         var ChildItemCodeValue= this.crmForm.crmFields.find(item=>{return item.key==='ChildItemID'}).value;
           if(ParentItemCodeValue!=null && ChildItemCodeValue!=null &&   ParentItemCodeValue[0].Id === ChildItemCodeValue[0].Id){
            this.$message.error('主物品不能等于子物品');
            return false;
         } 

        var failureTime='FailureTime';
        if(this.crmType==='bom' )
        {
          failureTime='ExpireTime'
        }
         var EffectiveTimeValue= this.crmForm.crmFields.find(item=>{return item.key==='EffectiveTime'}).value;
         var FailureTimeValue= this.crmForm.crmFields.find(item=>{return item.key===failureTime}).value;

         if(EffectiveTimeValue >= FailureTimeValue){
            this.$message.error('生效时间不能大于等于失效时间');
            return false;
         } 

      }
      return true;    
    },

    /* 提交 */
    submiteParams(params) {
      this.loading = true;
      if (this.action.type == "update") {
        this.submiteUpdateRequest(params);
      }
      //新增
      else {
        this.submiteAddRequest(params);
      }
    },

    submiteAddRequest(params) {
      let crmRequest = this.getSubmiteRequest();
      console.log("ID:" +this.action.id);
      //子主表保存的参数类型是数组
      if (
        this.crmType == "dictssub" ||
        this.crmType == "stdCostPriceDetail" ||
        this.crmType == "inventoryRouteDetail" ||
        this.crmType == "purchasePriceDetail" ||
        this.crmType == "routeDetail" ||
        this.crmType == "salePriceDetail"
      ) {
        let newParams = [];
        newParams.push(params);
        crmRequest(this.action.id, newParams)
          .then((res) => {
            this.submiteParamsCallBack(res);
          })
          .catch((error) => {
            this.loading = false;
            // this.$message.error(error.message); 系统已经默认弹出提示
            console.log(error.details);
          });
      } //其他表保存的参数类型是单独Dto
      else {
        crmRequest(params)
          .then((res) => {
            this.submiteParamsCallBack(res);
          })
          .catch((err) => {
            //唯一索引重复
            if(err.message==='An error occurred while updating the entries. See the inner exception for details.')
            {
              //SqlException 返回的异常消息 ,包括唯一索引重复
              if(err.details.indexOf('SqlException: '))
              {
                let beginindex= err.details.indexOf('SqlException: ')
                let endindex= err.details.indexOf('语句已终止。')
                //语句已终止。
                let message=  err.details.substring(beginindex, endindex);
                this.$message.error(message);
              }
              
            }
            else
            {
              //this.$message.error(err.message); 系统已经默认弹出提示
            }
            console.log(err.details);
            this.loading = false;
          });
      }
    },

    submiteUpdateRequest(params) {
      console.log("ID:" +this.action.id);
      console.log("ID:" +params);

      let crmRequest = this.getSubmiteUpdateRequest();
      if (
        this.crmType == "dictssub" ||
        this.crmType == "stdCostPriceDetail" ||
        this.crmType == "inventoryRouteDetail" ||
        this.crmType == "purchasePriceDetail" ||
        this.crmType == "routeDetail" ||
        this.crmType == "salePriceDetail"
      ) {
        let newParams = [];
        newParams.push(params);
        console.log("parentID:" +this.action.id);
        crmRequest(this.action.id, newParams)
          .then((res) => {
            this.submiteParamsCallBack(res);
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        crmRequest(this.action.id, params)
          .then((res) => {
            this.submiteParamsCallBack(res);
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },

    submiteParamsCallBack(res) {
      this.loading = false;
      this.hidenView();
      this.$message.success(
        this.action.type == "update" ? "编辑成功" : "添加成功"
      );
      // 回到保存成功
      this.$emit("save-success", {
        type: this.crmType,
        data: res.data || {},
        saveAndCreate: this.saveAndCreate,
      });
    },

    /**获取详情url**/
    getReadRequest(crmTypes = this.crmType) {
      console.log(
        "----- 方法 : 获取详情url getReadRequest(crmTypes = " + crmTypes + ")"
      );
      if (crmTypes == "leads") {
        return crmLeadsRead;
      } else if (crmTypes == "dicts") {
        return crmDictsRead;
      } else if (crmTypes == "dictssub") {
        return crmDictsItemDetailRead;
      } else if (crmTypes == "transaction") {
        return crmTransactionRead;
      } else if (crmTypes == "strategy") {
        return crmStrategyRead;
      } else if (crmTypes == "rule") {
        return crmRuleRead;
      } else if (crmTypes == "strategyRules") {
        return crmStrategyRulesRead;
      } else if (crmTypes == "verification") {
        return crmVerificationRead;
      } else if (crmTypes == "stage") {
        return crmStageRead;
      } else if (crmTypes == "customer") {
        return crmCustomerRead;
      } else if (crmTypes == "slgItem") {
        return crmSlgItemRead;
      } else if (crmTypes == "bom") {
        return crmBomRead;
      } else if (crmTypes == "uomGroup") {
        //add-fdw
        return crmUomGroupRead;
      } else if (crmTypes == "uom") {
        //add-fdw
        return crmUomRead;
      } else if (crmTypes == "interfaceCalendar") {
        return crmInterfaceCalendarRead;
      } else if (crmTypes == "verificationStages") {
        return crmVerificationStagesRead;
      } else if (crmTypes == "area") {
        // 区域
        return crmAreaRead;
      } else if (crmTypes == "areaItem") {
        // 区域-物品
        return crmAreaItemRead;
      } else if (crmTypes == "currency") {
        // 货币
        return crmCurrencyRead;
      } else if (crmTypes == "currencyExchange") {
        // 货币换算
        return crmCurrencyExchangeRead;
      } else if (crmTypes == "customerBom") {
        // 客户物品产品结构
        return crmCustomerBomRead;
      } else if (crmTypes == "customerItem") {
        // 客户物品
        return crmCustomerItemRead;
      } else if (crmTypes == "eqptType") {
        // 器具类型
        return crmEqptTypeRead;
      } else if (crmTypes == "eqptTypeItem") {
        // 器具类型-物品
        return crmEqptTypeItemRead;
      } else if (crmTypes == "item") {
        // 物品
        return crmItemRead;
      } else if (crmTypes == "itemTransTypeInventoryRoute") {
        // 物品-事务类型-物流路线分配
        return crmItemTransTypeInventoryRouteRead;
      } else if (crmTypes == "itemTransTypeOpStrategy") {
        // 物品-事务类型-工序-策略分配
        return crmItemTransTypeOpStrategyRead;
      } else if (crmTypes == "loc") {
        // 库位
        return crmLocRead;
      } else if (crmTypes == "machine") {
        // 机器
        return crmMachineRead;
      } else if (crmTypes == "param") {
        // 参数
        return crmParamRead;
      } else if (crmTypes == "port") {
        // 收货口
        return crmPortRead;
      } else if (crmTypes == "prodLine") {
        // 生产线
        return crmProdLineRead;
      } else if (crmTypes == "prodLineItem") {
        // 生产线-物品
        return crmProdLineItemRead;
      } else if (crmTypes == "project") {
        // 项目
        return crmProjectRead;
      } else if (crmTypes == "shift") {
        // 班次
        return crmShiftRead;
      } else if (crmTypes == "slg") {
        // 库位组
        return crmSlgRead;
      } else if (crmTypes == "supplier") {
        // 供应商
        return crmSupplierRead;
      } else if (crmTypes == "supplierItem") {
        // 供应商物品
        return crmSupplierItemRead;
      } else if (crmTypes == "team") {
        // 班组
        return crmTeamRead;
      } else if (crmTypes == "uomConversion") {
        // 计量单位转换
        return crmUomConversionRead;
      } else if (crmTypes == "wlg") {
        // 工作组
        return crmWlgRead;
      } else if (crmTypes == "wlgItem") {
        // 工作组-物品
        return crmWlgItemRead;
      } else if (crmTypes == "workCalendar") {
        // 工作日历
        return crmWorkCalendarRead;
      } else if (crmTypes == "workCenter") {
        // 工作中心
        return crmWorkCenterRead;
      } else if (crmTypes == "inventoryRoute") {
        // 物流路线
        return crmInventoryRouteRead;
      } else if (crmTypes == "inventoryRouteDetail") {
        // 物流路线明细
        return crmInventoryRouteDetailRead;
      } else if (crmTypes == "purchasePriceDetail") {
        // 采购价格单明细
        return crmPurchasePriceDetailRead;
      } else if (crmTypes == "purchasePriceSheet") {
        // 采购价格单
        return crmPurchasePriceSheetRead;
      } else if (crmTypes == "route") {
        // 工艺路线
        return crmRouteRead;
      } else if (crmTypes == "routeDetail") {
        // 工艺路线明细
        return crmRouteDetailRead;
      } else if (crmTypes == "salePriceDetail") {
        // 销售价格单明细
        return crmSalePriceDetailRead;
      } else if (crmTypes == "salePriceSheet") {
        // 销售价格单
        return crmSalePriceSheetRead;
      } else if (crmTypes == "stdCostPriceDetail") {
        // 标准成本价格明细
        return crmStdCostPriceDetailRead;
      } else if (crmTypes == "stdCostPriceSheet") {
        // 标准成本价格单
        return crmStdCostPriceSheetRead;
      } else if (
        crmTypes == "purchaseUomConversion" ||
        crmTypes == "stockUomConversion" ||
        crmTypes == "productionUomConversion" ||
        crmTypes == "sellUomConversion"
      ) {
        // 采购计量单位转换等
        return crmUomConversionRead;
      }
    },
    /** 获取上传url */
    getSubmiteUpdateRequest() {
      if (this.crmType == "leads") {
        return crmLeadsUpdate;
      } else if (this.crmType == "dicts") {
        return crmDictsUpdate;
      } else if (this.crmType == "dictssub") {
        return crmDictsItemUpdate;
      } else if (this.crmType == "transaction") {
        return crmTransactionUpdate;
      } else if (this.crmType == "strategy") {
        return crmStrategyUpdate;
      } else if (this.crmType == "rule") {
        return crmRuleUpdate;
      } else if (this.crmType == "strategyRules") {
        return crmStrategyRulesUpdate;
      } else if (this.crmType == "verification") {
        return crmVerificationUpdate;
      } else if (this.crmType == "stage") {
        return crmStageUpdate;
      } else if (this.crmType == "customer") {
        return crmCustomerUpdate;
      } else if (this.crmType == "slgItem") {
        return crmSlgItemUpdate;
      } else if (this.crmType == "bom") {
        return crmBomUpdate;
      } else if (this.crmType == "uomGroup") {
        //add-fdw
        return crmUomGroupUpdate;
      } else if (this.crmType == "uom") {
        //add-fdw
        return crmUomUpdate;
      } else if (this.crmType == "interfaceCalendar") {
        return crmInterfaceCalendarUpdate;
      } else if (this.crmType == "verificationStages") {
        return crmVerificationStagesUpdate;
      } else if (this.crmType == "area") {
        // 区域
        return crmAreaUpdate;
      } else if (this.crmType == "areaItem") {
        // 区域-物品
        return crmAreaItemUpdate;
      } else if (this.crmType == "currency") {
        // 货币
        return crmCurrencyUpdate;
      } else if (this.crmType == "currencyExchange") {
        // 货币换算
        return crmCurrencyExchangeUpdate;
      } else if (this.crmType == "customerBom") {
        // 客户物品产品结构
        return crmCustomerBomUpdate;
      } else if (this.crmType == "customerItem") {
        // 客户物品
        return crmCustomerItemUpdate;
      } else if (this.crmType == "eqptType") {
        // 器具类型
        return crmEqptTypeUpdate;
      } else if (this.crmType == "eqptTypeItem") {
        // 器具类型-物品
        return crmEqptTypeItemUpdate;
      } else if (this.crmType == "item") {
        // 物品
        return crmItemUpdate;
      } else if (this.crmType == "itemTransTypeInventoryRoute") {
        // 物品-事务类型-物流路线分配
        return crmItemTransTypeInventoryRouteUpdate;
      } else if (this.crmType == "itemTransTypeOpStrategy") {
        // 物品-事务类型-工序-策略分配
        return crmItemTransTypeOpStrategyUpdate;
      } else if (this.crmType == "loc") {
        // 库位
        return crmLocUpdate;
      } else if (this.crmType == "machine") {
        // 机器
        return crmMachineUpdate;
      } else if (this.crmType == "param") {
        // 参数
        return crmParamUpdate;
      } else if (this.crmType == "port") {
        // 收货口
        return crmPortUpdate;
      } else if (this.crmType == "prodLine") {
        // 生产线
        return crmProdLineUpdate;
      } else if (this.crmType == "prodLineItem") {
        // 生产线-物品
        return crmProdLineItemUpdate;
      } else if (this.crmType == "project") {
        // 项目
        return crmProjectUpdate;
      } else if (this.crmType == "shift") {
        // 班次
        return crmShiftUpdate;
      } else if (this.crmType == "slg") {
        // 库位组
        return crmSlgUpdate;
      } else if (this.crmType == "supplier") {
        // 供应商
        return crmSupplierUpdate;
      } else if (this.crmType == "supplierItem") {
        // 供应商物品
        return crmSupplierItemUpdate;
      } else if (this.crmType == "team") {
        // 班组
        return crmTeamUpdate;
      } else if (this.crmType == "uomConversion") {
        // 计量单位转换
        return crmUomConversionUpdate;
      } else if (this.crmType == "wlg") {
        // 工作组
        return crmWlgUpdate;
      } else if (this.crmType == "wlgItem") {
        // 工作组-物品
        return crmWlgItemUpdate;
      } else if (this.crmType == "workCalendar") {
        // 工作日历
        return crmWorkCalendarUpdate;
      } else if (this.crmType == "workCenter") {
        // 工作中心
        return crmWorkCenterUpdate;
      } else if (this.crmType == "inventoryRoute") {
        // 物流路线
        return crmInventoryRouteUpdate;
      } else if (this.crmType == "inventoryRouteDetail") {
        // 物流路线明细
        return crmInventoryRouteDetailUpdate;
      } else if (this.crmType == "purchasePriceDetail") {
        // 采购价格单明细
        return crmPurchasePriceDetailUpdate;
      } else if (this.crmType == "purchasePriceSheet") {
        // 采购价格单
        return crmPurchasePriceSheetUpdate;
      } else if (this.crmType == "route") {
        // 工艺路线
        return crmRouteUpdate;
      } else if (this.crmType == "routeDetail") {
        // 工艺路线明细
        return crmRouteDetailUpdate;
      } else if (this.crmType == "salePriceDetail") {
        // 销售价格单明细
        return crmSalePriceDetailUpdate;
      } else if (this.crmType == "salePriceSheet") {
        // 销售价格单
        return crmSalePriceSheetUpdate;
      } else if (this.crmType == "stdCostPriceDetail") {
        // 标准成本价格明细
        return crmStdCostPriceDetailUpdate;
      } else if (this.crmType == "stdCostPriceSheet") {
        // 标准成本价格单
        return crmStdCostPriceSheetUpdate;
      }
    },
    /** 获取创建方法 */
    getSubmiteRequest() {
      if (this.crmType == "leads") {
        return crmLeadsSave;
      } else if (this.crmType == "dicts") {
        return crmDictsSave;
      } else if (this.crmType == "dictssub") {
        return crmDictsItemAdd;
      } else if (this.crmType == "transaction") {
        return crmTransactionSave;
      } else if (this.crmType == "strategy") {
        return crmStrategySave;
      } else if (this.crmType == "rule") {
        return crmRuleSave;
      } else if (this.crmType == "strategyRules") {
        return crmStrategyRulesSave;
      } else if (this.crmType == "verification") {
        return crmVerificationSave;
      } else if (this.crmType == "stage") {
        return crmStageSave;
      } else if (this.crmType == "customer") {
        return crmCustomerSave;
      } else if (this.crmType == "slgItem") {
        return crmSlgItemSave;
      } else if (this.crmType == "bom") {
        //add-引入bom
        return crmBomSave;
      } else if (this.crmType == "uomGroup") {
        //add-引入uomgroup
        return crmUomGroupSave;
      } else if (this.crmType == "uom") {
        //add-引入uomgroup
        return crmUomSave;
      } else if (this.crmType == "interfaceCalendar") {
        return crmInterfaceCalendarSave;
      } else if (this.crmType == "verificationStages") {
        return crmVerificationStagesSave;
      } else if (this.crmType == "area") {
        // 区域
        return crmAreaSave;
      } else if (this.crmType == "areaItem") {
        // 区域-物品
        return crmAreaItemSave;
      } else if (this.crmType == "currency") {
        // 货币
        return crmCurrencySave;
      } else if (this.crmType == "currencyExchange") {
        // 货币换算
        return crmCurrencyExchangeSave;
      } else if (this.crmType == "customerBom") {
        // 客户物品产品结构
        return crmCustomerBomSave;
      } else if (this.crmType == "customerItem") {
        // 客户物品
        return crmCustomerItemSave;
      } else if (this.crmType == "eqptType") {
        // 器具类型
        return crmEqptTypeSave;
      } else if (this.crmType == "eqptTypeItem") {
        // 器具类型-物品
        return crmEqptTypeItemSave;
      } else if (this.crmType == "item") {
        // 物品
        return crmItemSave;
      } else if (this.crmType == "itemTransTypeInventoryRoute") {
        // 物品-事务类型-物流路线分配
        return crmItemTransTypeInventoryRouteSave;
      } else if (this.crmType == "itemTransTypeOpStrategy") {
        // 物品-事务类型-工序-策略分配
        return crmItemTransTypeOpStrategySave;
      } else if (this.crmType == "loc") {
        // 库位
        return crmLocSave;
      } else if (this.crmType == "machine") {
        // 机器
        return crmMachineSave;
      } else if (this.crmType == "param") {
        // 参数
        return crmParamSave;
      } else if (this.crmType == "port") {
        // 收货口
        return crmPortSave;
      } else if (this.crmType == "prodLine") {
        // 生产线
        return crmProdLineSave;
      } else if (this.crmType == "prodLineItem") {
        // 生产线-物品
        return crmProdLineItemSave;
      } else if (this.crmType == "project") {
        // 项目
        return crmProjectSave;
      } else if (this.crmType == "shift") {
        // 班次
        return crmShiftSave;
      } else if (this.crmType == "slg") {
        // 库位组
        return crmSlgSave;
      } else if (this.crmType == "supplier") {
        // 供应商
        return crmSupplierSave;
      } else if (this.crmType == "supplierItem") {
        // 供应商物品
        return crmSupplierItemSave;
      } else if (this.crmType == "team") {
        // 班组
        return crmTeamSave;
      } else if (this.crmType == "uomConversion") {
        // 计量单位转换
        return crmUomConversionSave;
      } else if (this.crmType == "wlg") {
        // 工作组
        return crmWlgSave;
      } else if (this.crmType == "wlgItem") {
        // 工作组-物品
        return crmWlgItemSave;
      } else if (this.crmType == "workCalendar") {
        // 工作日历
        return crmWorkCalendarSave;
      } else if (this.crmType == "workCenter") {
        // 工作中心
        return crmWorkCenterSave;
      } else if (this.crmType == "inventoryRoute") {
        // 物流路线
        return crmInventoryRouteSave;
      } else if (this.crmType == "inventoryRouteDetail") {
        // 物流路线明细
        return crmInventoryRouteDetailAdd;
      } else if (this.crmType == "purchasePriceSheet") {
        // 采购价格单
        return crmPurchasePriceSheetSave;
      } else if (this.crmType == "purchasePriceDetail") {
        // 采购价格单明细
        return crmPurchasePriceDetailAdd;
      } else if (this.crmType == "route") {
        // 工艺路线
        return crmRouteSave;
      } else if (this.crmType == "routeDetail") {
        // 工艺路线明细
        return crmRouteDetailAdd;
      } else if (this.crmType == "salePriceSheet") {
        // 销售价格单
        return crmSalePriceSheetSave;
      } else if (this.crmType == "salePriceDetail") {
        // 销售价格单明细
        return crmSalePriceDetailAdd;
      } else if (this.crmType == "stdCostPriceSheet") {
        // 标准成本价格单
        return crmStdCostPriceSheetSave;
      } else if (this.crmType == "stdCostPriceDetail") {
        // 标准成本价格明细
        return crmStdCostPriceDetailAdd;
      }
    },
    /** 拼接上传传输 */
    getSubmiteParams(array) {
      console.log(array)
      var params = { entity: {}, field: [] };
      for (let index = 0; index < array.length; index++) {
        const element = array[index];

        if (element.data.fieldType == 1) {
          params.entity[element.key] = this.getRealParams(element);
          //params.entity[element.key] = this.getRealParams(element) || ''
        } else {
          //枚举列表的fieldType==0
          element.data.value = this.getRealParams(element);
          params.field.push(element.data);
        }
      }
      return params.entity;
    },
    /** 获取其他参数 nxt */
    getOtherParams(params) {
      console.log("this.crmType : " + this.crmType);
      //新增
      if (this.action.type != "update") {
        // if (this.crmType == "dicts") {
        //   params["DictionaryItems"] = this.subtableData;
        // } else 
        //增加组织ID参数
        if (
          this.crmType === "area" ||
          this.crmType === "team" ||
          this.crmType === "port" ||
          this.crmType === "project" ||
          this.crmType === "wlg" ||
          this.crmType === "param" ||
          this.crmType === "stdCostPriceSheet" ||
          this.crmType === "inventoryRoute" ||
          this.crmType === "purchasePriceSheet" ||
          this.crmType === "route" ||
          this.crmType === "salePriceSheet" ||
          this.crmType === "stdCostPriceDetail" ||
          this.crmType === "inventoryRouteDetail" ||
          this.crmType === "purchasePriceDetail" ||
          this.crmType === "routeDetail" ||
          this.crmType === "salePriceDetail" ||
          this.crmType == "areaItem" ||
          this.crmType == "customer" ||
          this.crmType == "customerBom" ||
          this.crmType == "customerItem" ||
          this.crmType == "eqptTypeItem" ||
          this.crmType == "item" ||
          this.crmType == "itemTransTypeInventoryRoute" ||
          this.crmType == "itemTransTypeOpStrategy" ||
          this.crmType == "loc" ||
          this.crmType == "machine" ||
          this.crmType == "prodLineItem" ||
          this.crmType == "slg" ||
          this.crmType == "supplier" ||
          this.crmType == "supplierItem" ||
          this.crmType == "wlgItem" ||
          this.crmType == "workCenter" ||
          this.crmType == "bom" ||
          this.crmType == "prodLine" ||
          this.crmType == "slgItem"||
          this.crmType == "interfaceCalendar"||
          this.crmType == "workCalendar"||
          this.crmType == "shift"
        ) {
          //获取当前登录用户的组织ID
          console.log('Lockr.get("currentorgID")' + Lockr.get("currentorgID"));
          params["OrgID"] = Lockr.get("currentorgID");

        }
      } //修改
      else {
        params["Id"] = this.action.subid;
        //子表修改时要有Id

        if (this.crmType == "dictssub") {
          params["ItemName"] = this.crmData["ItemName"];
        } else if (this.crmType === "inventoryRouteDetail") {
          params["AreaID"] = this.crmData["AreaID"];
          params["TaskType"] = this.crmData["TaskType"];
        } else if (this.crmType === "purchasePriceDetail") {
          params["ItemID"] = this.crmData["ItemID"];
          params["BeginTime"] = this.crmData["BeginTime"];
        } else if (this.crmType === "stdCostPriceDetail") {
          params["ItemID"] = this.crmData["ItemID"];
          params["BeginTime"] = this.crmData["BeginTime"];
        } else if (this.crmType === "routeDetail") {
          params["ItemID"] = this.crmData["ItemID"];
          params["OperateProcess"] = this.crmData["OperateProcess"];
        } else if (this.crmType === "salePriceDetail") {
          params["ItemID"] = this.crmData["ItemID"];
          params["BeginTime"] = this.crmData["BeginTime"];
        }
      }
    },

    // 获取控件值
    getRealParams(element) {
      if (element.key == "OrgID") {
        return Lockr.get("currentorgID");
      }
      //关联表
      else if (element.key.endsWith("ID") && element.data.formType !== "text") {
        if (element.value && element.value.length) {
          return element.value[0].Id;
        } else {
          return null;
        }
      } else if (element.data.formType == "select") {
        //element.data.value的值应该从element.data.Setting中取
        if (element.value == "是") {
          element.value = true;
        } else if (element.value == "否") {
          element.value = false;
        }
      } else if (element.data.formType == "switch") {
        //如果不设置defaultValue element.value为""
        if (element.value == true || element.value === "" || element.value === null) {
          element.value = true;
        } else if (element.value == false) {
          element.value = false;
        }
      } else if(element.data.formType == "int" || element.data.formType == "number" || element.data.formType == "number2" || 
                element.data.formType == "number4" || element.data.formType == "moneynumber" || 
                element.data.formType == "mobile" || element.data.formType == "email" || element.data.formType == "rate" )
      {
        if(element.value === "" || element.value === null )     
        {
          element.value =0;
          //element.value =element.data.isNull===1? 0:null;
        }
      }else if(element.data.formType == "datetime")
      {
        if(element.value === "" || element.value === null)     
        {
          element.value = this.getNowDate();
        }
      }
      return element.value;
    },
    hidenView() {
      this.$emit("hiden-view");
    },
    // 根据类型获取标题展示名称
    getTitle() {
      let type=this.crmTypes[this.crmType];
      if(type===undefined)
      { 
        return ''
      }
      else
      {
        let name= type.name
        if(this.action.type == "create" || this.action.type == "save")
        {
          return '新增'+name;
        }
        else if(this.action.type == "update")
        {
          return '编辑'+name;

        }
        else if(this.action.type == "detail")
        {
          return name+'详细信息';
        }   
      }   
    },
    // 获取左边padding
    getPaddingLeft(item, index) {
      if (item.showblock && item.showblock == true) {
        return "0";
      }
      return item.styleIndex % 2 == 0 ? "0" : "25px";
    },
    // 获取左边padding
    getPaddingRight(item, index) {
      if (item.showblock && item.showblock == true) {
        return "0";
      }
      return item.styleIndex % 2 == 0 ? "25px" : "0";
    },
    // 上传之前的格式设置
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/png" ||
        file.type === "image/gif" ||
        file.type === "image/jpg" ||
        file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG,PNG,GIF,JPEG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      this.multfileImg = file;
      return isJPG && isLt2M;
    },
    httpRequest(data) {
      let _this = this;
      let rd = new FileReader(); // 创建文件读取对象
      let file = data.file;
      rd.readAsDataURL(file); // 文件读取装换为base64类型
      rd.onloadend = function (e) {
        _this.dialogImageUrl = this.result; // this指向当前方法onloadend的作用域
      };
    },
    // 上传文件个数超过定义的数量
    handleExceed(files, fileList) {
      //this.$message.warning(`当前限制选择 1 个文件`)
    },

    getNowDate() {
      var nowDate = new Date();
      var date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        day: nowDate.getDate()
        // hour: nowDate.getHours(),
        // minute: nowDate.getMinutes(),
        // second: nowDate.getSeconds(),
      };

      var year = date.year;
      var month = date.month >= 10 ? date.month : "0" + date.month;
      var date = date.day >= 10 ? date.day : "0" + date.day;
      // var hour = date.hour >=10 ? date.hour: '0' +date.hour;
      // var minute = date.minute >=10 ? date.minute: '0' +date.minute;
      // var second = date.second >=10 ? date.second: '0' +date.second;

      // var systemDate =date.year + "-" + month + "-" + date +' ' + hour + ':' + minute + ':' + second;

      var systemDate = year + "-" + month + "-" + date + " 00:00:00";
      return systemDate;
    },

    //2021年1月15日前代码
    // 获取自定义字段
    getField_Old() {
      console.log("");
      console.log("");
      this.loading = true;
      console.log("----- 获取自定义字段 data -----");
      console.log(data);
      console.log("this.crmType : " + this.crmType);
      const filedList = data[this.crmType].data;
      console.log("----- filedList -----");
      console.log(filedList);
      const filedListEdit = dataupdate[this.crmType].data;

      // 获取自定义字段的更新时间
      var params = {
        label: crmTypeModel[this.crmType],
      };
      // 进行编辑操作
      if (this.action.type == "update") {
        console.log("----- 进行编辑操作 -----");
        console.log("this.action.type : " + this.action.type);
        params.id = this.action.id;
        params.subid = this.action.subid;
        let crmRequest = this.getReadRequest();
        console.log(crmRequest);
        crmRequest(params.id, params.subid)
          .then((res) => {
            console.log("----- 循环字段开始 -----");
            filedListEdit.map((item) => {
              //获取JSON的KEY和value
              Object.keys(res).forEach((key) => {
                if (
                  key == item.fieldName &&
                  key.includes("ID") &&
                  item.formType != "text"
                ) {
                  console.log("----- 字段特殊判断 : 显示字段不是Name的 -----");
                  // 字段特殊判断
                  // if(item.formType == 'item'){
                  //   console.log('----- 字段特殊处理 : item-----')
                  //   crmItemRead(res[key]).then(resinner => {
                  //     let _json = {};
                  //     _json["Name"] = resinner.Code;
                  //     _json['Id'] = res[key]
                  //     var _array = [_json]
                  //     item.value = _array
                  //   })
                  // } else {
                  console.log("----- 准备获取对应列表接口 -----");
                  let ReadRequest = this.getReadRequest(item.formType);
                  console.log(ReadRequest);
                  if (ReadRequest == undefined || ReadRequest == "") {
                    console.log(
                      "------ 没有找到 " +
                        item.formType +
                        " 的 crmXXXXRead -----"
                    );
                  } else {
                    ReadRequest(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                  //}
                } else if (
                  key !== "OrgID" &&
                  key !== "ItemID" &&
                  key !== "SlgID" &&
                  key !== "UomID" &&
                  key !== "UomGroupID" &&
                  key !== "BasicUomID" &&
                  key !== "PurchaseUomConversionID" &&
                  key !== "StockUomConversionID" &&
                  key !== "ProductionUomConversionID" &&
                  key !== "SellUomConversionID" &&
                  key !== "ProjectID" &&
                  key !== "InventoryRouteID" &&
                  key !== "AllocationID"
                ) {
                  if (key == item.fieldName) {
                    item.value = res[key];
                    //  if(item.value==true){
                    //    item.value='是'
                    //  }else if(item.value==false){
                    //    item.value='否'
                    //  }
                  }
                } else if (key === "OrgID") {
                  if (key == item.fieldName) {
                    crmOrgRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["branchName"] = resinner.name;
                      _json[key] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                } else if (key === "ItemID") {
                  if (key == item.fieldName) {
                    console.log("ItemID" + res[key]);
                    crmItemRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                } else if (key === "SlgID") {
                  if (key == item.fieldName) {
                    console.log("SlgID" + res[key]);
                    crmSlgRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                } else if (key === "UomID") {
                  if (key == item.fieldName) {
                    console.log("UomID" + res[key]);
                    crmUomRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                } else if (key === "UomGroupID") {
                  if (key == item.fieldName) {
                    console.log("UomGroupID" + res[key]);
                    crmUomGroupRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                } else if (key === "BasicUomID") {
                  if (key == item.fieldName) {
                    console.log("BasicUomID" + res[key]);
                    crmUomGroupRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                } else if (key === "PurchaseUomConversionID") {
                  if (key == item.fieldName) {
                    crmUomConversionRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                } else if (key === "StockUomConversionID") {
                  if (key == item.fieldName) {
                    crmUomConversionRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                } else if (key === "ProductionUomConversionID") {
                  if (key == item.fieldName) {
                    crmUomConversionRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                } else if (key === "SellUomConversionID") {
                  if (key == item.fieldName) {
                    crmUomConversionRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                } else if (key === "ProjectID") {
                  if (key == item.fieldName) {
                    crmProjectRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                } else if (key === "InventoryRouteID") {
                  if (key == item.fieldName) {
                    crmInventoryRouteRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                } else if (key === "AllocationID") {
                  if (key == item.fieldName) {
                    crmInventoryRouteRead(res[key]).then((resinner) => {
                      let _json = {};
                      _json["Name"] = resinner.Name;
                      _json["Id"] = res[key];
                      var _array = [_json];
                      item.value = _array;
                    });
                  }
                }
              });
            });
            console.log("----- 循环字段结束 -----");
            this.loading = false;

            setTimeout((item) => {
              this.getcrmRulesAndModel(filedListEdit);
            }, 500);
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        console.log("----- 添加 -----");
        this.getcrmRulesAndModel(filedList);
      }
      this.loading = false;
    },

    getRealParams_Old(element) {
      if (
        element.key == "customer_id" ||
        element.key == "contacts_id" ||
        element.key == "business_id" ||
        element.key == "leads_id" ||
        element.key == "contract_id"
      ) {
        if (element.value && element.value.length) {
          const key = element.key.replace("_id", "Id");
          return element.value[0][key];
        } else {
          return "";
        }
      } else if (element.key == "OrgID") {
        return Lockr.get("currentorgID");
        // if (element.value && element.value.length) {
        //   //return element.value[0].OrgID
        //   return Lockr.get("currentorgID")
        // } else {
        //   return ''
        // }
      } else if (
        element.key == "UomID" ||
        element.key == "SlgID" ||
        element.key == "ItemID" ||
        element.key == "RuleID" ||
        element.key == "StrategyID" ||
        element.key == "UomGroupID" ||
        element.key == "BasicUomID" ||
        element.key == "PurchaseUomConversionID" ||
        element.key == "StockUomConversionID" ||
        element.key == "ProductionUomConversionID" ||
        element.key == "SellUomConversionID" ||
        element.key == "ProjectID" ||
        element.key == "InventoryRouteID" ||
        element.key == "VerificationID" ||
        element.key == "StageID" ||
        element.key.includes("ID") ||
        element.key.includes("Id")
      ) {
        if (element.value && element.value.length) {
          return element.value[0].Id;
        } else {
          return "";
        }
      } else if (element.data.formType == "select") {
        if (element.value == "是") {
          element.value = true;
        } else if (element.value == "否") {
          element.value = false;
        }
      } else if (element.data.formType == "switch") {
        //如果不设置defaultValue element.value为""
        if (element.value === "" || element.value == true) {
          element.value = true;
        } else if (element.value == false) {
          element.value = false;
        }
      } else if (
        element.data.formType == "user" ||
        element.data.formType == "structure"
      ) {
        return element.value
          .map(function (item, index, array) {
            return element.data.formType == "user" ? item.userId : item.id;
          })
          .join(",");
      } else if (element.data.formType == "file") {
        if (element.value && element.value.length > 0) {
          return element.value[0].batchId;
        }
        return "";
      } else if (element.key == "category_id") {
        if (element.value && element.value.length > 0) {
          return element.value[element.value.length - 1];
        }
        return "";
      } else if (element.data.formType == "checkbox") {
        if (element.value && element.value.length > 0) {
          return element.value.join(",");
        }
        return "";
      }
      // //将bool转成string类型
      // switch(element.value){
      //   case true:
      //     element.value = 'true'
      //     break;
      //   case false:
      //     element.value = 'false'
      //     break;
      // }
      return element.value;
    },
    // 根据自定义字段获取自定义字段规则
    getcrmRulesAndModel_Old(list) {
      console.log("----- 根据自定义字段获取自定义字段规则 -----");
      let showStyleIndex = -1;
      for (let index = 0; index < list.length; index++) {
        const item = list[index];
        showStyleIndex += 1;
        /**
         * 规则数据
         */
        this.crmRules[item.fieldName] = this.getItemRulesArrayFromItem(item);

        console.log("----- this.crmRules[item.fieldName] -----");
        console.log(this.crmRules[item.fieldName]);
        /**
         * 表单数据
         */
        if (
          // crm相关信息特殊处理
         
          item.formType == "contacts" ||
          item.formType == "customer" ||
          item.formType == "contract" ||
          item.formType == "business" ||
          item.formType == "receivables_plan" ||
          item.formType == "rule" ||
          item.formType == "org" ||
          item.formType == "slg" ||
          item.formType == "item" ||
          item.formType == "uom" ||
          item.formType == "uomGroup" ||
          item.formType == "interfaceCalendar" ||
          item.formType == "verificationStages" ||
          item.formType == "verification" ||
          item.formType == "stage" ||
          item.formType == "area" ||
          item.formType == "areaItem" ||
          item.formType == "currency" ||
          item.formType == "currencyExchange" ||
          item.formType == "customerBom" ||
          item.formType == "customerItem" ||
          item.formType == "eqptType" ||
          item.formType == "eqptTypeItem" ||
          item.formType == "itemTransTypeInventoryRoute" ||
          item.formType == "itemTransTypeOpStrategy" ||
          item.formType == "loc" ||
          item.formType == "machine" ||
          item.formType == "param" ||
          item.formType == "port" ||
          item.formType == "prodLine" ||
          item.formType == "prodLineItem" ||
          item.formType == "project" ||
          item.formType == "shift" ||
          item.formType == "slg" ||
          item.formType == "supplier" ||
          item.formType == "supplierItem" ||
          item.formType == "team" ||
          item.formType == "uomConversion" ||
          item.formType == "wlg" ||
          item.formType == "wlgItem" ||
          item.formType == "workCalendar" ||
          item.formType == "workCenter" ||
          item.formType == "dicts" ||
          item.formType == "inventoryRoute" ||
          item.formType == "stdCostPriceSheet" ||
          item.formType == "purchasePriceSheet" ||
          item.formType == "route" ||
          item.formType == "salePriceSheet"
        ) {
          var params = {};
          params["key"] = item.fieldName;
          params["data"] = item;

          // 获取 value relative 信息
          this.getParamsValueAndRelativeInfo(params, item, list);
          params["disabled"] = this.getItemDisabledFromItem(item);
          params["styleIndex"] = showStyleIndex;
          console.log("---------->" + JSON.stringify(params));
          this.crmForm.crmFields.push(params);
        } else {
          var params = {};
          if (
            item.formType == "user" ||
            item.formType == "structure" ||
            item.formType == "file" ||
            item.formType == "category" ||
            item.formType == "customer" ||
            item.formType == "business" ||
            item.formType == "contract"
          ) {
            //if (this.action.type == 'update'&& item.value)
            if (this.action.type == "update") {
              params["value"] = item.value ? objDeepCopy(item.value) : [];
            } else {
              params["value"] = item.defaultValue
                ? objDeepCopy(item.defaultValue)
                : [];
            }
          } else {
            if (this.action.type == "update") {
              params["value"] = item.value; // 编辑的值 在value∂ç字段
            } else {
              //params['value'] = item.defaultValue || ''
            }
          }
          params["key"] = item.fieldName;
          params["data"] = item;
          params["disabled"] = false; // 是否可交互
          params["styleIndex"] = showStyleIndex;
          this.crmForm.crmFields.push(params);
        }
      }
    },
    /**
     * 获取关联项的值 和 关联信息
     */
    getParamsValueAndRelativeInfo(params, item, list) {
      if (this.action.type == "relative") {
        const relativeData = this.action.data[item.formType];
        if (item.formType == "receivables_plan") {
          params["value"] = "";
        } else {
          params["value"] = relativeData ? [relativeData] : [];
        }
      } else {
        if (item.formType == "receivables_plan") {
          params["value"] = item.value || "";
        } else {
          params["value"] = item.value || [];
        }
      }
    },
    /**
     * 获取相关联item
     */
    getItemRelatveInfo(item, list, fromType) {
      let crmItem = null;
      if (this.action.type == "relative") {
        crmItem = this.action.data[fromType];
      } else {
        const crmObj = list.find((listItem) => {
          return listItem.formType === fromType;
        });
        if (crmObj && crmObj.value && crmObj.value.length > 0) {
          crmItem = crmObj.value[0];
        }
      }
      return crmItem;
    },
    /**
     * 获取关联项是否可操作
     */
    getItemDisabledFromItem(item) {
      // 相关添加
      if (this.action.type == "relative") {
        const relativeDisInfos = {
          business: {
            customer: { customer: true },
            contacts: { customer: true },
          },
          contacts: {
            customer: { customer: true },
            business: { customer: true },
          },
          contract: {
            customer: { customer: true },
            business: { customer: true, business: true },
          },
          receivables_plan: {
            contract: { customer: true, contract: true },
            customer: { customer: true },
          },
          receivables: {
            contract: { customer: true, contract: true },
            customer: { customer: true },
          },
        };
        // 添加类型
        const crmTypeDisInfos = relativeDisInfos[this.crmType];
        if (crmTypeDisInfos) {
          // 在哪个类型下添加
          const relativeTypeDisInfos = crmTypeDisInfos[this.action.crmType];
          if (relativeTypeDisInfos) {
            // 包含的字段值
            return relativeTypeDisInfos[item.formType] || false;
          }
        }
        return false;
      } else if (this.action.type != "update") {
        // 新建
        if (this.crmType === "contract" && item.formType === "business") {
          return true;
          // 回款下 新建 合同 和 回款计划 默认不能操作
        } else if (this.crmType === "receivables") {
          if (item.formType === "contract") {
            return true;
          } else if (item.formType === "receivables_plan") {
            return true;
          }
        }
      }
      return false;
    },
    /**
     * item 当行数据源
     */
    getItemRulesArrayFromItem(item) {
      var tempList = [];
      // 验证必填
      if (item.isNull == 1) {

        if(item.formType!=='switch')
          {
            tempList.push({
              required: true,
              message: item.name + "不能为空",
              trigger: ["blur"]
              // trigger: ["blur", "change"],
            });
          }
         
      }

      if(item.formType==='text') //增加长度校验
      {     
        tempList.push({
          min:0,
          max:36,
          message: "长度在1到36个字符",
          trigger: ["blur", "change"],
        });
      }
       

  
      // // 验证唯一
      // if (item.isUnique == 1) {
      //   var validateUnique = (rule, value, callback) => {
      //     if ((isArray(value) && value.length == 0) || !value) {
      //       callback();
      //     } else {
      //       var validatesParams = {};
      //       validatesParams.fieldId = item.fieldId;
      //       if (isArray(value)) {
      //         let postValue = "";
      //         if (value.length > 0) {
      //           if (
      //             rule.item.formType == "user" ||
      //             rule.item.formType == "structure"
      //           ) {
      //             postValue = value
      //               .map((valueItem) => {
      //                 return rule.item.formType == "user"
      //                   ? valueItem.userId
      //                   : valueItem.id;
      //               })
      //               .join(",");
      //           } else if (rule.item.fieldName == "categoryId") {
      //             if (value && value.length) {
      //               postValue = value[value.length - 1];
      //             } else {
      //               postValue = "";
      //             }
      //           } else if (rule.item.formType == "checkbox") {
      //             postValue = value.join(",");
      //           }
      //         }
      //         validatesParams.value = postValue;
      //       } else {
      //         validatesParams.value = value;
      //       }
      //       if (this.action.type == "update") {
      //         validatesParams.batchId = this.action.batchId;
      //       }
      //       //filedValidates(validatesParams)
      //       //   .then(res => {
      //       callback();
      //       // })
      //       // .catch(error => {
      //       //   callback(new Error(error.msg ? error.msg : '验证出错'))
      //       // })
      //     }
      //   };
      //   tempList.push({
      //     validator: validateUnique,
      //     item: item,
      //     trigger:
      //       item.formType == "checkbox" || item.formType == "select"
      //         ? ["change"]
      //         : ["blur"],
      //   });
      // }
      // 其他字符
      let validItem={item:item,trigger: ["blur"] };
      if (item.formType == "int") {
        var validateInt = (rule, value, callback) => {
          if (!value || value == "" || regexIsInt(value)) {
            callback();
          } else {
            callback(new Error("整数类型长度必须是小于12位的数字"));
          }
        };
        validItem.validator= validateInt;
        tempList.push(validItem);
      }
      else if (item.formType == "number") {
        var validateNumber = (rule, value, callback) => {
          if ( value == "" || regexIsNumber(value)) {
            callback();
          } else {
            callback(new Error("数字的整数部及小数部分须是整数"));
          }
        };
        validItem.validator= validateNumber;
        tempList.push(validItem);
      } 
      else if (item.formType == "number2") {
        var validateCRMNumber2 = (rule, value, callback) => {
          if (value == "" || regexIsCRMNumber2(value)) {
            callback();
          } else {
            callback(new Error("数字的整数部分须少于12位，小数部分须少于2位"));
          }
        };
        validItem.validator= validateCRMNumber2;
      } else if (item.formType == "number4") {
        var validateCRMNumber4 = (rule, value, callback) => {
          if (value == "" || regexIsCRMNumber4(value)) {
            callback();
          } else {
            callback(new Error("数字的整数部分须少于12位，小数部分须少于4位"));
          }
        };
        validItem.validator= validateCRMNumber4;
        tempList.push(validItem);
      } 
      else if (item.formType == "moneynumber") {
        var validateCRMMoneyNumber = (rule, value, callback) => {
          if (value == "" || regexIsCRMMoneyNumber(value)) {
            callback();
          } else {
            callback(new Error("货币的整数部分须少于10位，小数部分须少于4位"));
          }
        };
        validItem.validator= validateCRMMoneyNumber;
        tempList.push(validItem);
      } else if (item.formType == "mobile") {
        var validateCRMMobile = (rule, value, callback) => {
          if (value == "" || regexIsCRMMobile(value)) {
            callback();
          } else {
            callback(new Error("手机格式有误"));
          }
        };
        validItem.validator= validateCRMMobile;
        tempList.push(validItem);
      } else if (item.formType == "email") {
        var validateCRMEmail = (rule, value, callback) => {
          if (value == "" || regexIsCRMEmail(value)) {
            callback();
          } else {
            callback(new Error("邮箱格式有误"));
          }
        };
       validItem.validator= validateCRMEmail;
       tempList.push(validItem);
      }
      else if (item.formType == "rate") {
        var validateCRMRate = (rule, value, callback) => {
          if (value == "" || regexIsCRMRate(value)) {
            callback();
          } else {
             callback(new Error("税率/百分比应小于1，小数部分须少于6位"));
          }
        };
       validItem.validator= validateCRMRate;
       tempList.push(validItem);
      }

      //获取其他校验规则
      let otherRules= this.getOtherRulesArrayFromItem(item);
      if(otherRules.length>0)
      { 
        otherRules.forEach(item=>tempList.push(item));
      }
      return tempList;
    },
    /**
     * item 其他校验规则  getItemRulesArrayFromItem
     */
    getOtherRulesArrayFromItem(item)
    {
      var tempList = [];
      if(this.crmType==='interfaceCalendar')
      { 
        let InterfaceCalendarRules=this.getInterfaceCalendarRules(item);
   
        if(InterfaceCalendarRules.length>0){
            InterfaceCalendarRules.forEach(rule => {
            (tempList.push(rule));
          });
        }
      }

      
      // if(this.crmType==='strategyRules')
      // { 
      //   let strategyRules=this.getStrategyrules(item,list);
      //   strategyRules.forEach(item=>tempList.push(item));
      // }

      return tempList;
    },
    getProductParams(params, element) {
      if (element.value) {
        params["product"] = element.value.product ? element.value.product : [];
        params.entity["totalPrice"] = element.value.totalPrice
          ? element.value.totalPrice
          : 0;
        params.entity["discountRate"] = element.value.discountRate
          ? element.value.discountRate
          : 0;
      } else {
        params["product"] = [];
        params.entity["totalPrice"] = "";
        params.entity["discountRate"] = "";
      }
    },
    // 获取客户位置参数
    getCustomerAddressParams(params, element) {
      params["address"] = element.value.address
        ? element.value.address.join(",")
        : "";
      params["detailAddress"] = element.value.detailAddress;
      params["location"] = element.value.location;
      params["lng"] = element.value.lng;
      params["lat"] = element.value.lat;
    },
    getStrategyrules(item)
    {
      let list=this.crmForm.crmFields
      var tempList = [];
      let validItem={item:item,trigger: ["blur"] };
      if(item.fieldName==='EffectiveTime')
      {
        var validateEffectiveTime = (rule, value, callback) => {
          const ExpireTimeItem = list.find((listItem) => {
            return listItem.key === 'ExpireTime'; });

          const ExpireTimeValue=ExpireTimeItem.value;

          if(ExpireTimeValue!=null && value>= ExpireTimeValue )
          {
            callback(new Error("生效时间不能大于等于失效时间"));
          } else {

            //this.$refs.crmForm.validateField("crmFields." + ExpireTimeItem.styleIndex + ".value");
            callback();
          }
        }
        validItem.validator= validateEffectiveTime;
        tempList.push(validItem);
      }
      else if(item.fieldName==='ExpireTime')
      {
        var validateExpireTime = (rule, value, callback) => {
          const EffectiveItem = list.find((listItem) => {
            return listItem.key === 'EffectiveTime'; }).value;
            
          const EffectiveValue =EffectiveItem.value;

          if(EffectiveValue!=null && EffectiveValue>= value )
          {
            callback(new Error("失效时间时间不能小于等于生效时间"));
          } else {
            //this.$refs.crmForm.validateField("EffectiveItem." + ExpireTimeItem.styleIndex + ".value");
            callback();
          }
        }
        validItem.validator= validateExpireTime;
        tempList.push(validItem);
      }
      return tempList;
    },
    getInterfaceCalendarRules(item)
    {
      var tempList = [];
      let validItem={item:item,trigger: ["blur"] };
      if(item.fieldName==='Year') //
      {
        var validateYear = (rule, value, callback) => {
          if ( value>=2000 && value<=3000) {
            callback();
          } else {
            callback(new Error("年份应该在2000-3000之间"));
          }
        };
        validItem.validator= validateYear;
        tempList.push(validItem);
      }
      else if(item.fieldName==='Month') //
      {
        var validateEffectiveTime = (rule, value, callback) => {
           if ( value >=1 && value<=12) {
            callback();
          } else {
            callback(new Error("月份应该在1-12之间"));
          }
        }
        validItem.validator= validateEffectiveTime;
        tempList.push(validItem);
      }
      return tempList;
    }
  },
};
</script>
<style lang="scss" scoped>
.crm-create-container {
  position: relative;
  height: 100%;
}

.crm-create-flex {
  position: relative;
  overflow-x: hidden;
  overflow-y: auto;
  flex: 1;
}

.crm-create-header {
  height: 40px;
  margin-bottom: 20px;
  padding: 0 10px;
  flex-shrink: 0;
  .close {
    display: block;
    width: 40px;
    height: 40px;
    margin-right: -10px;
    padding: 10px;
    cursor: pointer;
  }
}

.crm-create-body {
  // flex: 1;
  overflow-x: hidden;
  // overflow-y: scroll;
  border-right: 1px;
  min-height: 350px;
  max-height: 550px;
  overflow-y: auto;
  padding: 20px;
}

/** 将其改变为flex布局 */
.crm-create-box {
  display: flex;
  flex-wrap: wrap;
  padding: 0 10px;
}

.crm-create-item {
  flex: 0 0 50%;
  flex-shrink: 0;
  // overflow: hidden;
  padding-bottom: 10px;
}

// 占用一整行
.crm-create-block-item {
  flex: 0 0 100%;
  flex-shrink: 0;
  padding-bottom: 10px;
}

.el-form-item /deep/ .el-form-item__label {
  line-height: normal;
  font-size: 13px;
  color: #333333;
  position: relative;
  padding-left: 8px;
  padding-bottom: 0;
}

.el-form /deep/ .el-form-item {
  margin-bottom: 0px;
}

.el-form /deep/ .el-form-item.is-required .el-form-item__label:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
  position: absolute;
  left: 0;
  top: 5px;
}

.handle-bar {
  position: relative;
  .handle-button {
    float: right;
    margin-top: 5px;
    margin-right: 20px;
  }
}

.el-button + .el-button {
  margin-left: 0;
}

// 审核信息 里的审核类型
.examine-type {
  font-size: 12px;
  color: white;
  background-color: #fd715a;
  padding: 0 8px;
  margin-left: 5px;
  height: 16px;
  line-height: 16px;
  border-radius: 8px;
  transform: scale(0.8, 0.8);
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
