import { message, notification } from 'antd'
import { extendInclude, extendRule, getDataFieldValue, initFilter, empty, extendOrder, guid, onBeforeSaveHandleRecordLog, auditOptionShow } from "../../utils/common";
export default {
  onBeforeSaveHandleRecord(params) {
    params.record.TaskID = params.data.TaskID    //TaskID传递消息表ID
    params.record.STATUSPLAN = params.customParams;
    onBeforeSaveHandleRecordLog(params, 'BS032', '前端日志')
  },
  onBeforeEdit: ({ isNew, login, stateData, data, setFieldEditable, getFieldValue, dispatch, ListCheckRiskArea, setFieldValueByBatch, setFieldVisible, setFieldValue }) => {

    if (!isNew) {
      if (stateData.Nav_CheckType != undefined) {
        setFieldEditable('Nav_CheckType.NAME', false)
        setFieldEditable('Nav_CheckTypeLevel.Nav_Enums.NAME', false)
      }

      if (stateData.CREACTTYPE == 10) {
        setFieldEditable('CHECKOBJECT', false)
      } else {
        if (getFieldValue('CHECKOBJECT') != null && getFieldValue('CHECKOBJECT') != 0) {
          setFieldEditable('CHECKOBJECT', false)
        }
      }

      auditOptionShow(stateData, stateData.STATUSPLAN, 30, 'AUDIT_OPINION', stateData.ID, dispatch, setFieldVisible)

      // auditOptionShow(stateData, dataState, stateReject, propName, dataId, dispatch, setFieldVisible)

      if (stateData?.Nav_ListSafeCheckDetail?.length > 50) {
        notification.info({
          message: <a style={{ color: 'red' }}>温馨提示</a>,
          description: '检查任务超过50条后会影响执行效率，请谨慎操作！',
          placement: 'bottomLeft',
        });
      }
    } else {
      setFieldVisible("AUDIT_OPINION", false)
      if (stateData.CHECKOBJECT == null && login?.user?.MineType?.indexOf(',') == -1 && login.user.MineType.length > 0) {
        setFieldValue("CHECKOBJECT", login.user.MineType)//只有一个生产单元
        setFieldEditable("CHECKOBJECT", false)//只有一个生产单元
      }
    }
  },

  onChange: ({ stateData, value, colInfo, getFieldValue, setFieldValue, dispatch, setFieldValueByBatch, getSubTableData, updateSubTableData }) => {
    if (colInfo.FIELD_NAME == "Nav_ListCheckProjectCategory" || colInfo.FIELD_NAME == "Nav_ListCheckRiskArea" || colInfo.FIELD_NAME == "Nav_ListCheckProject") {
      //填充数据  OrderPagedCheckMain
      var orgId = colInfo.ORG_ID;   //登录后有存储登录信息
      let json = initFilter(orgId);
      let CHECK_TYPE_ID = getFieldValue("CHECK_TYPE_ID")
      let CHECK_TYPE_LEVEL_ID = getFieldValue("CHECK_TYPE_LEVEL_ID")

      extendRule(json, 'Parameter2', 1, CHECK_TYPE_ID);
      extendRule(json, 'Parameter3', 1, getFieldValue("CHECKOBJECT"));
      extendRule(json, 'Parameter4', 1, CHECK_TYPE_LEVEL_ID);

      let listArea = getFieldValue("Nav_ListCheckRiskArea")
      let areaIDs = ""
      if (listArea != undefined && listArea.length > 0) {
        for (let i = 0; i < listArea.length; i++) {
          if (listArea[i].IS_DELETED == undefined || listArea[i].IS_DELETED == null || listArea[i].IS_DELETED == false)
            areaIDs += (areaIDs.length > 0 ? "," : "") + listArea[i].RISK_AREA_ID
        }
      }
      extendRule(json, 'Parameter5', 1, areaIDs);

      let listProject = getFieldValue("Nav_ListCheckProject")
      let ProjectIDs = ""
      if (listProject != undefined && listProject.length > 0) {
        for (let i = 0; i < listProject.length; i++) {
          if (listProject[i].IS_DELETED == undefined || listProject[i].IS_DELETED == null || listProject[i].IS_DELETED == false)
            ProjectIDs += (ProjectIDs.length > 0 ? "," : "") + listProject[i].CHECK_PROJECT_ID
        }
      }
      extendRule(json, 'Parameter6', 1, ProjectIDs);
      let valCategory = getFieldValue('Nav_ListCheckProjectCategory');
      let ProjectCategoryIDs = ""
      if (valCategory != undefined && valCategory.length > 0) {
        for (let i = 0; i < valCategory.length; i++) {
          if (valCategory[i].IS_DELETED == undefined || valCategory[i].IS_DELETED == null || valCategory[i].IS_DELETED == false)
            ProjectCategoryIDs += (ProjectCategoryIDs.length > 0 ? "," : "") + valCategory[i].CHECK_PROJECT_CATEGORY_ID
        }
      }
      extendRule(json, 'Parameter1', 1, ProjectCategoryIDs);
      extendRule(json, 'Keyword', 1, getFieldValue("ID"));
      if (areaIDs.length > 0 && ProjectIDs.length > 0 && ProjectCategoryIDs.length > 0 && CHECK_TYPE_ID != undefined && CHECK_TYPE_ID.length > 0 && CHECK_TYPE_LEVEL_ID != undefined && CHECK_TYPE_LEVEL_ID.length > 0) {
        dispatch({
          type: 'app/getDataByPost',
          url: 'BS/BSSafeCheck/OrderPagedSafeCheckDetail',
          payload: json,
          onlyData: false,
          onComplete: (ret) => {
            let temps = [];
            if (ret && ret.IsSuccessful && ret.Data) {
              let detail = ret.Data.map((item, i) => {
                item['ROW_NO'] = i + 1;
                return item;
              });
              temps.push({ field: "Nav_ListSafeCheckDetail", value: detail });

              if (detail.length > 50) {
                notification.info({
                  message: <a style={{ color: 'red' }}>温馨提示</a>,
                  description: '检查任务超过50条后会影响执行效率，请谨慎操作！',
                  placement: 'bottomLeft',
                });
              }

            } else {
              temps.push({ field: "Nav_ListSafeCheckDetail", value: null });
            }
            setFieldValueByBatch(temps);
          }
        });
      } else {
        if (stateData == undefined || (stateData != undefined && stateData.CREACTTYPE != undefined && stateData.CREACTTYPE != 30)) {
          let temps = [];
          temps.push({ field: "Nav_ListSafeCheckDetail", value: null });
          setFieldValueByBatch(temps);
        }
      }
    } else {
      if (colInfo != null && (colInfo.FIELD_NAME == "Nav_CheckTypeLevel.Nav_Enums.NAME" || colInfo.FIELD_NAME == "Nav_CheckType.NAME")) {
        // getFieldValue, setFieldValue
        var typeName = getFieldValue("Nav_CheckType.NAME")
        if (typeName == null || typeName == '') {
          const temps = [];
          temps.push({ field: 'Nav_CheckTypeLevel.Nav_Enums.NAME', value: null })
          temps.push({ field: 'NAME', value: '' })
          setFieldValueByBatch(temps);
        } else {
          var levelName = getFieldValue("Nav_CheckTypeLevel.Nav_Enums.NAME")
          setFieldValue("NAME", (levelName == null ? "" : levelName) + (typeName == null ? "" : typeName))
        }
      }
    }
  },

  onSubChange: ({ row, setDataState, pageCode, record, colInfo, dispatch, stateData, props }) => {
    //如果修改原有库 直接填写对应ID 
    // debugger
    if ((colInfo.FIELD_NAME != "ROW_NO") && (record.ISMAINCHANGE == undefined || record.ISMAINCHANGE == null || !record.ISMAINCHANGE)) {
      var MainId = record.CHECK_MAIN_ID
      if (MainId != null && MainId != undefined && MainId.length > 0) {
        stateData.Nav_ListSafeCheckDetail[record.ROW_NO - 1].ISMAINCHANGE = true
      }
    }

    if (colInfo.FIELD_NAME == "Nav_ListCheckDetailUser") {

      //更新选中人员
      let tmp = "";
      for (var x = 0; x < stateData.Nav_ListSafeCheckDetail.length; x++) {
        let users = stateData.Nav_ListSafeCheckDetail[x].Nav_ListCheckDetailUser
        if (users) {
          for (let i = 0; i < users.length; i++) {
            if (!users[i].IS_DELETED) {
              if (tmp.indexOf(users[i].Nav_User.NAME) == -1) {
                tmp += (tmp.length > 0 ? "," : "") + users[i].Nav_User.NAME
              }
            }
          }
        }
      }
      stateData.CheckUsers = tmp
      setDataState({ ...stateData });

    } else if (colInfo.FIELD_NAME == "QUESTION_LEVEL") {
      if (record.QUESTION_LEVEL == "10") {
        stateData.Nav_ListSafeCheckDetail[record.ROW_NO - 1].SERIOUS_RISK = 1
      } else {
        stateData.Nav_ListSafeCheckDetail[record.ROW_NO - 1].SERIOUS_RISK = 0
      }
    }



    // CheckUsers
    // setDataState("CheckUsers", "jianc")
    // if (colInfo.FIELD_NAME == "Nav_CheckType.NAME") {
    //   //只要檢查類型修改 清空  項目分類 檢查層級
    //   stateData.Nav_ListContentCheckTypes[0].Nav_CheckProjectCategory = []
    //   stateData.Nav_ListContentCheckTypes[0].Nav_ListContentCheckTypeLevels = []
    //   // if (record.Nav_CheckType.Name) {
    //   // } else {
    //   //   //清空項目分類 檢查層級
    //   // }
    // }
  },

  updateCheckUser: ({ row, pageCode, record, colInfo, resetFields, stateData, saveHeadRecord, saveRowRecord, getSelectedRecords, setState }) => {
    let DetailCheck = getSelectedRecords();
    if (DetailCheck && DetailCheck.length > 1) {
      let ListCheckUserFirst = DetailCheck[0].Nav_ListCheckDetailUser;
      //更新行数据
      for (let i = 1; i < DetailCheck.length; i++) {
        //组装数据
        let updateList = [];
        if (ListCheckUserFirst != undefined && ListCheckUserFirst.length > 0) {
          for (let j = 0; j < ListCheckUserFirst.length; j++) {
            if (!ListCheckUserFirst[j].IS_DELETED) {
              let updateObj = { ...ListCheckUserFirst[j] };
              updateObj["ID"] = guid()
              updateList.push(updateObj);
            }
          }
          let iRow = { ...DetailCheck[i] };
          iRow.Nav_ListCheckDetailUser = updateList;
          saveRowRecord({ record: iRow, editCode: "T_BS_SAFE_CHECK_DETAIL" })

          for (var x = 0; x < stateData.Nav_ListSafeCheckDetail.length; x++) {
            if (iRow.ID == stateData.Nav_ListSafeCheckDetail[x].ID) {
              stateData.Nav_ListSafeCheckDetail[x].Nav_ListCheckDetailUser = updateList;
            }
          }
        } else {
          //人员删除
          let iRow = { ...DetailCheck[i] };
          // iRow.Nav_ListCheckDetailUser = updateList;
          for (let j = 0; j < iRow.Nav_ListCheckDetailUser.length; j++) {
            iRow.Nav_ListCheckDetailUser[j].IS_DELETED = true
          }
          saveRowRecord({ record: iRow, editCode: "T_BS_SAFE_CHECK_DETAIL" })
          // for (var x = 0; x < stateData.Nav_ListSafeCheckDetail.length; x++) {
          //   if (iRow.ID == stateData.Nav_ListSafeCheckDetail[x].ID) {
          //     stateData.Nav_ListSafeCheckDetail[x].Nav_ListCheckDetailUser = updateList;
          //   }
          // }
        }

        //更新选中人员
        let tmp = "";
        for (var x = 0; x < stateData.Nav_ListSafeCheckDetail.length; x++) {
          let users = stateData.Nav_ListSafeCheckDetail[x].Nav_ListCheckDetailUser
          if (users) {
            for (let i = 0; i < users.length; i++) {
              if (!users[i].IS_DELETED) {
                if (tmp.indexOf(users[i].Nav_User.NAME) == -1) {
                  tmp += (tmp.length > 0 ? "," : "") + users[i].Nav_User.NAME
                }
              }
            }
          }
        }
        stateData.CheckUsers = tmp
        setState({ data: stateData });
      }
    }
  },
  handleRenderRowControl(params) {
    if (params.record.CREATE_TIME) {
      if (params.colConfig.field == 'Nav_CheckArea.NAME') {
        return <>
          {params.record.Nav_CheckArea?.NAME}
        </>
      }
      else if (params.colConfig.field == 'Nav_CheckProject.NAME') {
        return <>
          {params.record.Nav_CheckProject?.NAME}
        </>
      }
      else if (params.colConfig.field == 'Nav_CheckProjectCategory.NAME') {
        return <>
          {params.record.Nav_CheckProjectCategory?.NAME}
        </>
      }
      else if (params.colConfig.field == 'CHECKCONTENT') {
        return <>
          {params.record.CHECKCONTENT}
        </>
      }
    } else {
      return '';
    }
  },

  btnCancel: ({ record, onCancel, data, dispatch }) => {
    let json = initFilter(record.ORG_ID, record.ID, null, null, null, data.TaskID);
    dispatch({
      type: 'app/getDataByPost',
      url: 'BS/BSSafeCheck/Cancel',
      payload: json,
      onlyData: false,
      onComplete: (ret) => {
        message.success('执行成功', null, onCancel())
      }
    })
  },
}
