/**
 * @Author WangXu
 * @Date 2019/5/21
 * @Description: 任务模板创建的状态管理
 */
import Vue from 'vue';
import { saveAll, getTempletById } from '@/api/task';

/**
 * 数组去重添加方法
 * @param arr 数组
 * @param data 数据
 * @param key 重复的key
 */
function arrayAddItem(arr, data, key) {
  const keyType = typeof key;
  const flag = arr.findIndex((val, index, arr) => {
    // 单个key
    if (keyType === 'string') {
      return val[key] === data[key];
    }
    // 多个key
    if (Array.isArray(key)) {
      let temp =key.reduce((total, currentValue) => {
        return val[currentValue] === data[currentValue] && total;
      }, true);
      return temp
    }
    return val === data;
  });
  if (flag === -1) {
    arr.push(data);
  } else {
    arr[flag] = data;
  }
  return arr;
}
/**
 * 增加新表单方法
 * */
function addNewForm(workTemplateField,newForm) {
 workTemplateField.forEach(item => {
   if (item.form.length>0){
     let arr = newForm.filter(key => {
       for (let i = 0; i < item.form.length; i++) {
         if (key.fieldId && key.fieldId === item.form[i].fieldId) {
           return false
         } else if (key.fieldId && i === item.form.length - 1) {
           return true
         }
       }
     })
     item.form = item.form.concat(arr)
   } else{
     item.form = newForm
   }
 })
  workTemplateField.forEach(item => {
    let tempArr =newForm.map(key => {
      for (let i = 0; i < item.form.length; i++) {
        if (key.fieldId && key.fieldId === item.form[i].fieldId) {
          item.form[i].fieldOrder = key.fieldOrder
          item.form[i].fieldTp = key.fieldTp
          item.form[i].major = key.major
          item.form[i].print = key.print
          item.form[i].required = key.required
          item.form[i].fieldNm = key.fieldNm
          return item.form[i]
        }
      }
    })
    item.form = tempArr[0] ===undefined?[]:tempArr
  })
  return workTemplateField
}

const taskTemplate = {
  state: {
    workTemplate: {}, // 任务基础模板设置
    workTemplateField: [], // 任务页面设置
    createformData: [], // 任务创建第二步生成的数据
    activitiml: {}, // 任务流程设置
    workTemplateOtherSettings: {}, // 任务其他设置
    bpmnXml: '', // 任务流程xml
    workApproveList: [], // 审批人数据,
    fieldCondition: []
  },

  getters: {
    getFieldData: state => {
      return {
        createformData: state.createformData,
        workTemplateField: state.workTemplateField
      };
    },
    workTemplate: state => state.workTemplate,
    workApproveList: state => state.workApproveList,
    fieldCondition: state => state.fieldCondition,
    workTemplateOtherSettings: state => state.workTemplateOtherSettings,
    createRoles: state => state.workTemplate.createRoles || []
  },

  mutations: {
    SET_WORKTEMPLATE: (state, workTemplate) => {
      state.workTemplate = workTemplate;
    },
    SET_WORKTEMPLATE_CREATEROLES: (state, data) => {
      state.workTemplate.createRoles = data;
    },
    SET_FROMDATA: (state, data) => {
      state.createformData = data;
      // state.workTemplateField = fromData
    },
    SET_WORKTEMPLATEFIELD: (state, workTemplateField) => {
      state.workTemplateField = arrayAddItem(state.workTemplateField, workTemplateField, ['activityId', 'templateId']);
      // state.workTemplateField.push(workTemplateField);
      // state.workTemplateField[workTemplateField.activityId] = workTemplateField
    },
    SET_WORKTEMPLATEFIELDBYNEWFORM: (state, form) => {
      state.workTemplateField = addNewForm(state.workTemplateField, form)
      // state.workTemplateField.push(workTemplateField); state.workTemplateField[workTemplateField.activityId] = workTemplateField
    },
    SET_ACTIVITIML: (state, activitiml) => {
      state.activitiml = activitiml;
    },
    SET_BPMNXML: (state, bpmnXml) => {
      state.bpmnXml = bpmnXml;
    },
    SET_WORKTEMPLATEOTHERSETTINGS: (state, workTemplateOtherSettings) => {
      state.workTemplateOtherSettings = workTemplateOtherSettings;
    },
    SET_FIELDCONDITION: (state, data) => {
      // state.fieldCondition.push(data);
      state.fieldCondition = arrayAddItem(state.fieldCondition, data, ['activityId', 'templateId']);
      // state.fieldCondition[data.activityId] = data
    },
    SET_WORKAPPROVELIST: (state, data) => {
      // state.workApproveList.push(data);
      state.workApproveList = arrayAddItem(state.workApproveList, data, ['activityId', 'templateId']);

    },
    SET_TASKTEMPLATE: (state, {
      workTemplate,
      workTemplateField,
      activitiml,
      workTemplateOtherSettings,
      createformData,
      bpmnXml,
      workApproveList,
      fieldCondition
    }) => {
      state.workTemplate = workTemplate;
      state.workTemplateField = workTemplateField;
      state.activitiml = activitiml;
      state.workTemplateOtherSettings = workTemplateOtherSettings;
      state.createformData = createformData;
      state.bpmnXml = bpmnXml;
      state.workApproveList = workApproveList;
      state.fieldCondition = fieldCondition;
    }
  },

  actions: {
    /**
     * 发布按钮调用的事件
     * @param commit
     * @param state
     * @param workTemplate
     * @returns {Promise<any>}
     */
    saveTaskTemplate({ commit, state }, workTemplate) {
      return new Promise((resolve, reject) => {
        // commit('SET_WORKTEMPLATE', workTemplate)
        if (workTemplate.templateName){
          state.workTemplate.templateNm = workTemplate.templateName
        }
        console.log(state.workTemplate);
        let jsonStr = '';
        if (state.createformData.length !== 0) {
          jsonStr = JSON.stringify({ 'template': state.createformData });
          console.log(jsonStr);
        }
        // const promission = []
        // for (const key in state.workTemplateField) {
        //   promission.push(state.workTemplateField[key])
        // }
        const workApproveList = [];
        for (const item of state.workApproveList) {
          const temp = Object.assign(item, {
            personData: item.personData
              ? item.personData.toString()
              : ''
          });
          workApproveList.push(temp);
        }

        const processGatewayList = state.fieldCondition.map((value, key) => {
          let item;
          if (state.fieldCondition[key].conditionType === '1') {
            item = Object.assign({}, {
              approvalType: state.fieldCondition[key].approvalType,
              type: state.fieldCondition[key].conditionType,
              activityId: state.fieldCondition[key].activityId,
              templateId: state.fieldCondition[key].templateId,
              conditions: 'flag==' + state.fieldCondition[key].approvalType
            });
          }
          if (state.fieldCondition[key].conditionType === '2') {
            if (state.fieldCondition[key].formFieldCondition.operate !== 'between') {
              item = Object.assign({}, {
                type: state.fieldCondition[key].conditionType,
                activityId: state.fieldCondition[key].activityId,
                templateId: state.fieldCondition[key].templateId,
                fieldId: state.fieldCondition[key].formFieldModal.id,
                conditions: state.fieldCondition[key].formFieldModal.id +
                  state.fieldCondition[key].formFieldCondition.operate +
                  state.fieldCondition[key].formFieldCondition.condition
              });
            } else {
              item = Object.assign({}, {
                type: state.fieldCondition[key].conditionType,
                activityId: state.fieldCondition[key].activityId,
                templateId: state.fieldCondition[key].templateId,
                fieldId: state.fieldCondition[key].formFieldModal.id,
                conditions: state.fieldCondition[key].formFieldCondition.condition1 +
                  state.fieldCondition[key].formFieldCondition.operate1 +
                  state.fieldCondition[key].formFieldModal.id + '&&' +
                  state.fieldCondition[key].formFieldModal.id +
                  state.fieldCondition[key].formFieldCondition.operate2 +
                  state.fieldCondition[key].formFieldCondition.condition2
              });
            }
          }
          if (state.fieldCondition[key].conditionType === '3') {
            item = Object.assign({}, {
              approvalType: state.fieldCondition[key].approvalType,
              type: state.fieldCondition[key].conditionType,
              activityId: state.fieldCondition[key].activityId,
              templateId: state.fieldCondition[key].templateId,
              conditions: 'deptId==' + state.fieldCondition[key].deptCondition
            });
          }
          return item;
        });

        console.log(processGatewayList);
        saveAll({
          fieldJsonStr: jsonStr,
          templateId: state.workTemplate.id,
          xmlJson: state.bpmnXml,
          permissionJson: JSON.stringify(state.workTemplateField),
          workTemplate: Object.assign(state.workTemplate, {
            createRoles: state.workTemplate.createRoles
              ? state.workTemplate.createRoles.toString()
              : '',
            managerRoles: state.workTemplate.managerRoles
              ? state.workTemplate.managerRoles.toString()
              : ''
          }),
          workApproveList: workApproveList,
          workTemplateOtherSettings: Object.keys(state.workTemplateOtherSettings).length === 0 ? null : state.workTemplateOtherSettings,
          processGatewayList
        })
          .then(res => {
            resolve(res);
          });
      });
    },
    QueryTempletBytempId({ commit, state }, { templateId }) {
      return new Promise((resolve, reject) => {
        getTempletById({ templateId })
          .then(res => {
            // const workPermission = {}
            // for (const key in res.data.activitiml.workPermission) {
            //   const template = res.data.activitiml.workPermission[key]
            //   workPermission[key] = Object.assign({}, {
            //     templateId: res.data.workTemplate.templateId,
            //     activityId: key,
            //     template: template
            //   })
            // }
            let keyArr = ['fieldNm', 'fieldTp', 'required', 'print', 'major', 'id'];
            res.data.templateFormFieldList.forEach((item) => {
              let objItem = {};
              for (let key in item) {
                if (keyArr.includes(key)) {
                  objItem[key] = item[key];
                }
              }
              item['obj'] = objItem;
            });
            const fieldConditionData = res.data.activitiml.processGatewayList || [];

            const fieldCondition = fieldConditionData.map((item) => {
              const type = item.type
              let obj = {}
              if (type === '1') {
                const reg = new RegExp('==', 'g');
                const conditionData = item.conditions.split(reg);
                console.log('fieldCondition1', conditionData)
                obj = {
                  activityId: item.activityId,
                  conditionType: item.type,
                  templateId: item.templateId,
                  approvalType: conditionData[1] || ''
                };
              }
              if (type === '2') {
                const reg = new RegExp('>=|<=|>|<|=|&&', 'g');
                const conditionData = item.conditions.split(reg);
                console.log('conditionData', conditionData.length);
                let condition = {};
                if (conditionData.length === 2) {
                  condition = {
                    condition: conditionData[1],
                    operate: item.conditions.match(reg)[0]
                  };
                } else {
                  condition = {
                    condition1: conditionData[0],
                    operate1: item.conditions.match(reg)[0],
                    condition2: conditionData[3],
                    operate2: item.conditions.match(reg)[2],
                    operate: 'between'
                  };
                }
                obj = {
                  activityId: item.activityId,
                  conditionType: item.type,
                  templateId: item.templateId,
                  formFieldCondition: condition,
                  formFieldModal: item.templateFormFieldDO
                };
              }
              if (type === '3') {
                const reg = new RegExp('deptId==', 'g');
                const conditionData = item.conditions.split(reg);
                obj = {
                  activityId: item.activityId,
                  conditionType: item.type,
                  templateId: item.templateId,
                  deptCondition: conditionData[1] || ''
                };
              }

              return obj;
            });
            commit('SET_TASKTEMPLATE', {
              workTemplate: res.data.workTemplate, // 任务基础模板设置
              workTemplateField: res.data.activitiml.workPermission, // 任务页面设置
              createformData: res.data.templateFormFieldList, // 任务创建第二步生成的数据
              activitiml: res.data.activitiml, // 任务流程设置
              workTemplateOtherSettings: res.data.workTemplateOtherSettings || {}, // 任务其他设置
              bpmnXml: res.data.activitiml.xmlPath, // 任务流程xml
              workApproveList: res.data.activitiml.workApproveList, // 审批人数据
              fieldCondition: fieldCondition
            });
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    CleanTempletBytempId({ commit, state }) {
      commit('SET_TASKTEMPLATE', {
        workTemplate: [], // 任务基础模板设置
        workTemplateField: [], // 任务页面设置
        createformData: [], // 任务创建第二步生成的数据
        activitiml: {}, // 任务流程设置
        workTemplateOtherSettings: {}, // 任务其他设置
        bpmnXml: '', // 任务流程xml
        workApproveList: [], // 审批人数据
        fieldCondition: []
      });
      return new Promise((resolve, reject) => {
        console.log('CleanTempletBytempId');
        resolve();
      });
    },
    saveWorkTemplate({ commit, state }, workTemplate) {
      return new Promise((resolve, reject) => {
        commit('SET_WORKTEMPLATE', workTemplate);
        console.log('SET_WORKTEMPLATE', workTemplate);
        resolve();
      });
    },
    saveWorkTemplateCreateRole({ commit, state }, data) {
      return new Promise((resolve, reject) => {
        commit('SET_WORKTEMPLATE_CREATEROLES', data);
        console.log('SET_WORKTEMPLATE_CREATEROLES', data);
        resolve();
      });
    },
    saveWorkTemplateField({ commit, state }, data) {
      return new Promise((resolve, reject) => {
        for (const obj in state.workTemplateField) {
          const data2 = JSON.parse(JSON.stringify(data));
          const workTemplateFieldObj = new Map();
          const data1 = state.workTemplateField[obj].template;
          if (data1 !== undefined) {
            data1.forEach((item) => {
              workTemplateFieldObj.set(item.fieldId, item.permission);
            });
            data2.forEach((item) => {
              if (workTemplateFieldObj.get(item.fieldId) === undefined) {
                item.permission = '';
              } else {
                item.permission = workTemplateFieldObj.get(item.fieldId);
              }
            });
            state.workTemplateField[obj].template = data2;
          }
        }
        commit('SET_FROMDATA', data);
        resolve();
      });
    },
    saveFlowElementFormField({ commit, state }, data) {
      return new Promise((resolve, reject) => {
        commit('SET_WORKTEMPLATEFIELD', data);
        resolve();
      });
    },
    saveNewFlowElementFormField({ commit, state }, data) {
      return new Promise((resolve, reject) => {
        commit('SET_WORKTEMPLATEFIELDBYNEWFORM', data);
        resolve();
      });
    },
    saveBpmn({ commit, state }, data) {
      return new Promise((resolve, reject) => {
        commit('SET_BPMNXML', data);
        resolve();
      });
    },
    saveApprover({ commit, state }, data) {
      return new Promise((resolve, reject) => {
        commit('SET_WORKAPPROVELIST', data);
        resolve();
      });
    },
    saveFieldCondition({ commit, state }, data) {
      return new Promise((resolve, reject) => {
        commit('SET_FIELDCONDITION', data);
        resolve(state.fieldCondition);
      });
    },
    saveWorkTemplateOtherSettings({ commit, state }, data) {
      return new Promise((resolve, reject) => {
        commit('SET_WORKTEMPLATEOTHERSETTINGS', data);
        resolve();
      });
    }
  }

};

export default taskTemplate;
