<template>
  <basic-container>
    <div class="box-dashed flex">
      <div class="retain-box">
        <el-checkbox v-model="isRetain"></el-checkbox>
        <span>保留</span>
        <el-input-number
          v-model="retainNum"
          :step="1"
          :disabled="!isRetain"
          size="small"
        ></el-input-number>
        <span class="retain">位</span>
      </div>
      <div>
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          @select="handleSelect"
        >
          <el-submenu v-for="(value,key,index) in formulaList" :key="key" :index="key">
            <template slot="title">
              <span>{{key}}</span>
            </template>
            <el-menu-item v-for="(item2,index2) in value" :key="index2" :index="(index+1) +'-' + (index2+1)">{{item2.name}}</el-menu-item>
          </el-submenu>
        </el-menu>
      </div>
    </div>
    <div class="box-dashed">
      <div class="mg-b-20">函数公式</div>
      <div class="edit-text">
        <span>
          <formula-item 
            v-for="(item,index) in resultFormula" :key="index" 
            :item="item" @click="obj => equationClick(obj,index,'resultFormula')"
          >
          </formula-item>
        </span>
        <span>=</span>
        <span>
          <formula-item 
            v-for="(item,index) in processFormula" :key="index" 
            :item="item" @click="obj => equationClick(obj,index,'processFormula')"
          >
          </formula-item>
        </span>
      </div>
      <div class="flex jc-sb">
        <div></div>
        <div><el-button type="info" size="small" @click="operationEdit">重置函数</el-button></div>
      </div>
    </div>
    <div v-show="operationVisible" class="operation-box">
      <div>选择参数设置</div>
      <div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card shadow="never">
              <el-scrollbar style="height: 460px">
                <el-tree
                  class="filter-tree"
                  lazy
                  :load="loadNode"
                  @node-click="getNodeDetail"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  highlight-current
                  node-key="id"
                  ref="tree"
                >
                </el-tree>
              </el-scrollbar>
            </el-card>
          </el-col>
          <el-col :span="16">
            <el-select v-model="eleTableId" @change="getTableEle" placeholder="请选择元素表">
              <el-option  v-for="item in eleTableList" :key="item.id" :label="item.tableName" :value="item.id"></el-option>
            </el-select>
            <div class="mg-t-10 mg-b-10 no-mb-col">
              <el-scrollbar style="height: 210px">
                <el-row>
                  <el-col :span="6" v-for="item in eleList" :key="item.id">
                    <div class="ele-box">
                      <span>{{item.eName}}</span>
                      <el-checkbox v-model="item.checked" @change="value => eleCheckHandle(value,item)"></el-checkbox>
                    </div>
                  </el-col>
                </el-row>
              </el-scrollbar>
            </div>
            <div class="flex jc-sb">
              <div>定位数据位置:</div>
              <div>
                <el-link :underline="false" type="primary" class="mg-r-20" @click="eleAddFormula">元素添加到公式</el-link>
                <el-link :underline="false" type="primary" class="mg-r-10" @click="addBrackets('(',false)">(</el-link>
                <el-link :underline="false" type="primary" class="mg-r-10" @click="addBrackets(')',true)">)</el-link>
                <!-- <el-link :underline="false" type="primary" class="mg-r-10" @click="addBrackets('[',false)">【</el-link>
                <el-link :underline="false" type="primary" class="mg-r-10" @click="addBrackets(']',true)">】</el-link> -->
                <el-link :underline="false" type="primary" @click="addText">输入值</el-link>
              </div>
            </div>
            <div class="border-grey sele-ele-box">
              <div>
                <formula-item 
                  v-for="(item,index) in selectEleFormula" :key="index" 
                  :item="item" @click="obj => eleFormulaClick(obj,index)"
                >
                </formula-item>
              </div>
            </div>
          </el-col>
        </el-row>
        <div class="text-align-c">
          <el-button size="small" @click="operationHandle" type="primary">保存</el-button>
          <el-button size="small" @click="operationVisible = false">取消</el-button>
        </div>
      </div>
    </div>
    <div v-show="!operationVisible && !showFunDetail">
      <div class="box-dashed">
        <div class="mg-b-20">函数公式运算执行溯源</div>
        <div>
          <el-select
            v-model="projectId"
            @change="projectChange"
            placeholder="请选择项目"
            style="width: 380px"
          >
            <el-option
              v-for="item in projectList"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-select v-model="contractId" placeholder="请选择合同段">
            <el-option
              v-for="item in contractList"
              :key="item.id"
              :label="item.contractName"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button type="info">查询</el-button>
        </div>
      </div>
      <div class="text-align-c">
        <el-button type="warning">取消</el-button>
        <el-button type="primary" @click="saveFormula">保存</el-button>
      </div>
    </div>
    <div v-if="!operationVisible && showFunDetail">
      <el-tabs v-model="actiFunIndex" closable @tab-remove="removeFun" :before-leave="funLeave">
        <el-tab-pane v-for="(item,index) in equationSelectEle.children" :key="index" :label="item.name" :name="index.toString()">
          <formula-template :formulainfo="item" :curele="equationSelectEle" @sele-ele-handle="showChooseEle">
            
          </formula-template>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog title="输入值" :visible.sync="inputVisible" width="300px" append-to-body :close-on-click-modal="false">
      <el-input v-model="inputText" placeholder="请输入内容"></el-input>
      <div class="text-align-c mg-t-10">
        <el-button size="small" @click="addTextHandle" type="primary">保存</el-button>
        <el-button size="small" @click="inputVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择元素" :visible.sync="chooseEleVisible" width="800px" append-to-body :close-on-click-modal="false">
      <div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card shadow="never">
              <el-scrollbar style="height: 460px">
                <el-tree
                  class="filter-tree"
                  lazy
                  :load="loadNode"
                  @node-click="getNodeDetail"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  highlight-current
                  node-key="id"
                  ref="tree"
                >
                </el-tree>
              </el-scrollbar>
            </el-card>
          </el-col>
          <el-col :span="16">
            <el-select v-model="eleTableId" @change="getTableEle" placeholder="请选择元素表">
              <el-option  v-for="item in eleTableList" :key="item.id" :label="item.tableName" :value="item.id"></el-option>
            </el-select>
            <div class="mg-t-10 mg-b-10 no-mb-col">
              <el-scrollbar style="height: 210px">
                <el-row>
                  <el-col :span="6" v-for="item in eleList" :key="item.id">
                    <div class="ele-box">
                      <span>{{item.eName}}</span>
                      <el-checkbox v-model="item.checked" @change="value => eleCheckHandle(value,item)"></el-checkbox>
                    </div>
                  </el-col>
                </el-row>
              </el-scrollbar>
            </div>
          </el-col>
        </el-row>
        <div class="text-align-c">
          <el-button size="small" @click="chooseEleHandle" type="primary">保存</el-button>
          <el-button size="small" @click="chooseEleVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getLazytree,selectByNodeTable,selectFormElements} from "@/api/manager/wbstree";
import { getProjectList } from "@/api/manager/projectinfo";
import { findContractByProjectId } from "@/api/manager/contractinfo";
import { getDetail as getEleDeatil } from "@/api/manager/wbsformelement";
import { getTypeMap,saveFormula,formulaDetail,updateFormula } from "@/api/formula/formula";
import {mapGetters} from "vuex";

import formulaItem from "./component/formulaItem"
import formulaTemplate from "./component/formulaTemplate"

import {formulaArrayToString} from "./formulaArrayToString"
import {formulaStringToArray} from "./formulaStringToArray"
export default {
  components: {
    formulaItem,
    formulaTemplate
  },
  data() {
    return {
      wbsid: "", //从哪个wbs树过来的
      eleid: "", //元素id
      formulaid:'',

      isRetain: false, //是否保留小数
      retainNum: 2, //保留几位小数
      formulaList:{},
      formulaMap:{},
      activeIndex: "1-1", //当前选择的公式

      projectList: [], //项目备选列表
      projectId: "", //溯源的项目ID
      curProjiect: {}, //当前项目对象
      contractList: [], //合同段备选列表
      contractId: "", //合同段id

      operationVisible: false, //基础运算弹窗
      defaultProps: {
        children: "children",
        label: "title",
        isLeaf: function (data) {
          return !data.hasChildren || (data.isExistForm==1);
        },
      },
      eleTableId:'',//选中的元素表id
      eleTableList:[],
      eleList:[],
      selectEleFormula:[],
      curSeleEleIndex:0,//公式文字里面选中的元素索引
      inputVisible:false,//输入弹窗
      inputText:"",//输入值

      resultFormula:[],//=等号左边的数组
      processFormula:[],//=等号右边的数组
      processType:'',//选中的元素在等号哪边
      processSelectIndex:0,//选中的索引
      actiFunIndex:0,//元素下挂载的计算式的索引
      chooseEleVisible:false,//选择元素弹窗
      argumenObj:{},

      symbolReg:/(\+|-|\*|\/)（.+）/,
      operatorReg : /^\+|-|\*|%/,//加减乘除
      startFCRegExp : /^FC\.([a-zA-Z]+)\(/,// 匹配开始的FC.xxx(
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),

    // selectEleFormulaText:function(){
    //   let text = '';
    //   this.selectEleFormula.forEach((Element)=>{
    //     text+=Element.name;
    //   })
    //   return text
    // }

    //等式中选中的元素
    equationSelectEle:function(){
      if(this.processType){
        return this[this.processType][this.processSelectIndex];
      }else{  
        return null;
      }
    },

    //是否显示元素下挂载的计算式信息
    showFunDetail:function(){
      if(this.equationSelectEle && this.equationSelectEle.children && this.equationSelectEle.children.length>0){
        return true;
      }else{
        return false;
      }
    }
  },
  created() {
    this.wbsid = this.$route.query.wbsid;
    this.eleid = this.$route.query.eleid;
    this.init();
  },
  methods: {
    async init() {
      this.getEleDeatil();
      this.getProjectList();
      await this.getTypeMap();

      this.formulaStringToArray();
    },

    //懒加载树
    loadNode(node, resolve) {
      let pid = 0;
      if (node.level != 0) {
        pid = node.data.id;
      }
      getLazytree(this.wbsid, pid, this.userInfo.tenant_id).then((res) => {
        let arr = [];
        if (Array.isArray(res.data.data)) {
          arr = res.data.data;
        }
        return resolve(arr);
      });
    },

    //获取项目列表
    getProjectList() {
      getProjectList(1, 999).then((res) => {
        this.projectList = res.data.data.records;
      });
    },

    //选择公式处理
    handleSelect(index,indexPath) {
      //console.log(index,'index')
      //console.log(indexPath,'indexPath')
      if(this.operationVisible){
        this.openerationSelect(index,indexPath)
      }else{
        this.equationSelect(index,indexPath)
      }
    },

    //在选择元素模式下点选计算式
    openerationSelect(index,indexPath){
      if(indexPath[0]!='基础运算'){
        this.$message({
          type: "warning",
          message: "当前只能使用基础运算"
        });
        return;
      }
      let formulaindex = Number(indexPath[1].split('-')[1])-1;
      this.eleAddFormulaHandle(this.formulaList[indexPath[0]][formulaindex]);
    },

    //溯源项目id切换
    projectChange(id) {
      for (let i = 0; i < this.projectList.length; i++) {
        if (id == this.projectList[i].id) {
          this.curProjiect = this.projectList[i];
          //根据项目id获取合同段列表
          findContractByProjectId(this.curProjiect.id).then((res) => {
            this.contractList = res.data.data;
            this.contractId = "";
          });
          return;
        }
      }
    },

    operationEdit(){
      this.selectEleFormula= JSON.parse(JSON.stringify(this.processFormula));
      this.operationVisible = true;
    },

    eleAddFormula(){
      for (let i = 0; i < this.eleList.length; i++) {
        if (this.eleList[i].checked) {
          this.eleAddFormulaHandle(this.eleList[i]);
          break;
        }
      }
    },

    //把元素加到公式里
    eleAddFormulaHandle(ele){
      if(ele.tableElementKey){
        //元素
        this.selectEleFormula.push({
          type:'Element',
          name:ele.eName,
          id:ele.id,
          selected:false,
          tableElementKey:ele.tableElementKey,
          children:[],
        })
      }else if(ele.template && ele.example){
        //运算符号
        this.selectEleFormula.push({
          type:'Operator',
          name:this.symbolReg.exec(ele.name)[1],
          selected:false,
          template:ele.template
        })
      }else if(ele.type == 'Brackets'){
        //括号
        this.selectEleFormula.splice(ele.selectIndex,0,{
          type:'Brackets',
          name:ele.name,
          selected:false,
        })
      }else if(ele.type == 'Text'){
        //输入值
        this.selectEleFormula.push({
          type:'Text',
          name:ele.name,
          selected:false,
        })
      }
    },

    //添加括号
    addBrackets(text,type){
      //type 是true 表示在元素右边插入
      if(this.curSeleEleIndex == Number(this.curSeleEleIndex)){
        this.eleAddFormulaHandle({
          type:'Brackets',
          name:text,
          selectIndex:type?Number(this.curSeleEleIndex)+1:this.curSeleEleIndex
        })
        //如果在左边插入index要增1
        if(!type){
          this.curSeleEleIndex = Number(this.curSeleEleIndex)+1;
        }
      }
    },

    
    addText(){
      this.inputVisible = true;
    },
    //添加输入值
    addTextHandle(){
      this.eleAddFormulaHandle({
        type:'Text',
        name:this.inputText
      })
      this.inputVisible = false;
    },

    //勾选元素
    eleCheckHandle(checked,item){
      if(checked){
        this.eleList.forEach((ele)=>{
          this.$set(ele,'checked',false);
          //ele.checked = false;
        })
        item.checked = true;
      }
    },

    //点选公式中的元素
    eleFormulaClick({selected,item},index){
      if(selected){
        this.selectEleFormula.forEach((ele)=>{
          ele.selected = false;
        })
        item.selected = true;
        this.curSeleEleIndex = index;
      }else{
        this.curSeleEleIndex = 0;
      }
    },

    //赋值给等号右边的数组
    operationHandle(){
      this.processFormula = JSON.parse(JSON.stringify(this.selectEleFormula));
      this.operationVisible = false;
    },

    //点选等式中的元素
    equationClick({selected,item},index,arrName){
      if(selected){
        this.resultFormula.forEach((ele)=>{
          ele.selected = false;
        })
        this.processFormula.forEach((ele)=>{
          ele.selected = false;
        })
        this.processSelectIndex = index;
        this.processType = arrName;
        item.selected = true;
      }else{
        this.processType = '';
      }
    },

    //在等式模式下点选计算式
    equationSelect(index,indexPath){
      if(!this.equationSelectEle ||(this.equationSelectEle && this.equationSelectEle.type != 'Element') ){
        this.$message({
          type: "warning",
          message: "请先选中元素"
        });
        return;
      }

      let formulaindex = Number(indexPath[1].split('-')[1])-1;
      let expression = this.formulaList[indexPath[0]][formulaindex];
      if(expression.type ==1){
        return;
      }
      //console.log(JSON.parse(expression.template));
      let obj = Object.assign({}, expression);
      //obj.template = JSON.parse(obj.template);
      obj.arguments = new Array(obj.template.args.length);
      obj.arguments[0] = {
          id:this.equationSelectEle.id,
          name:this.equationSelectEle.name,
          selected:false,
          tableElementKey:this.equationSelectEle.tableElementKey,
          type:"Element",
      };
      this.equationSelectEle.children.push(obj);
    },

    //选择元素
    chooseEleHandle(){
      for (let i = 0; i < this.eleList.length; i++) {
        if (this.eleList[i].checked) {
          let ele = this.eleList[i]
          let obj = {
            type:'Element',
            name:ele.eName,
            id:ele.id,
            selected:false,
            tableElementKey:ele.tableElementKey,
            children:[],
          }
          this.$set(this.argumenObj.arguments,this.argumenObj.index,obj);
          this.chooseEleVisible = false;
          break;
        }
      }
    },

    //显示选择元素弹窗
    showChooseEle(argumenObj){
      this.argumenObj = argumenObj;
      this.chooseEleVisible = true;
    },

    //移除挂载的函数
    removeFun(name){
      //console.log(name)
      this.equationSelectEle.children.splice(Number(name), 1);
    },

    //切换公式tab标签
    funLeave(activeName, oldActiveName){
      if(oldActiveName){
        let formula = this.equationSelectEle.children[Number(oldActiveName)];
        if(formula){
          return this.checkFormulaLegal(formula);
        }
      }
      
    },

    //检测公式合法
    checkFormulaLegal(formula){
      if(!formula.arguments){
        return false;
      }

      //当前选中的元素
      let curEle = this.equationSelectEle;
      let isIn = false;
      for (let i = 0; i < formula.arguments.length; i++) {
        if(formula.arguments[i] && formula.arguments[i].id ==curEle.id){
          isIn = true;
          break;
        }
      }
      if(!isIn){
        this.$message({
          type: "warning",
          message: "参数必须有一个值是当前元素"
        });
        return false;
      }

      return true;
    },

    //保存公式
    saveFormula(){
      let obj = formulaArrayToString(this.processFormula,this.resultFormula);
      //console.log(text);
      if(this.formulaid){
        updateFormula({
          id:this.formulaid,
          formula:obj.text,
          remark:'',
          wbsId:this.wbsid,
          elementId:this.eleid,
          map:JSON.stringify(obj.eleMap)
        }).then(()=>{
          this.$message({
            type: "success",
            message: "修改成功"
          });
        })
      }else{
        saveFormula({
          formula:obj.text,
          remark:'',
          wbsId:this.wbsid,
          elementId:this.eleid,
          map:JSON.stringify(obj.eleMap)
        }).then(()=>{
          this.$message({
            type: "success",
            message: "保存成功"
          });
        })
      }
      
    },

    //把公式文本还原数组
    async formulaStringToArray(){
      let detail = (await formulaDetail({elementId:this.eleid})).data.data;
      //console.log(detail);
      if(detail.id){
        this.formulaid = detail.id;
        let formula = formulaStringToArray(detail.formula,detail.map,this.formulaMap);
        this.processFormula = formula.processFormula;
        formula.resultFormula[0].id = this.resultFormula[0].id;
        formula.resultFormula[0].name = this.resultFormula[0].name;
        formula.resultFormula[0].tableElementKey = this.resultFormula[0].tableElementKey;
        this.resultFormula[0].children = formula.resultFormula[0].children;
      }
    },

    getNodeDetail(data) {
      selectByNodeTable(data.id).then((res)=>{
        if(res.data.data.length){
          this.eleTableList = res.data.data;
        }else{
          this.eleTableList = [];
        }
      })
    },

    getEleDeatil(){
      getEleDeatil(this.eleid).then((res)=>{
        let ele = res.data.data;
        this.resultFormula = [{
          type:'Element',
          name:ele.eName,
          id:ele.id,
          selected:false,
          tableElementKey:ele.tableElementKey,
          children:[],
        }]
      })
    },

    getTableEle(tableId){
      selectFormElements(tableId).then((res)=>{
        this.eleList = res.data.data;
      })
    },

    getTypeMap(){
      return new Promise((resolve)=>{
        getTypeMap().then((res)=>{
          //console.log(res)
          this.formulaList = res.data.data;

          //生成map，方便查找
          for (let key in this.formulaList) {
            if(typeof(this.formulaList[key]) == 'object'){
              this.formulaList[key].forEach((formula)=>{
                formula.template =  JSON.parse(formula.template);
                if(this.operatorReg.test(formula.template.ft)){
                  this.formulaMap[formula.template.ft] = formula;
                }else if(this.startFCRegExp.test(formula.template.ft)){
                  let regRes = formula.template.ft.match(this.startFCRegExp);
                  this.formulaMap[regRes[0]] = formula;
                }
              })
            }
          }
        }).finally(() => {
          resolve();
        })
      })
    }
  },
};
</script>

<style scoped lang="scss">
.box-dashed {
  border: 1px dashed #bbbbbb;
  border-radius: 6px;
  padding: 10px;
  margin-bottom: 10px;
}
.retain-box {
  border-right: 1px dashed #bbbbbb;
}
.retain {
  line-height: 50px;
  margin-right: 10px;
}
.edit-text {
  font-size: 26px;
  margin-left: 20px;
}

.el-menu--popup .el-menu-item.is-active {
  background-color: #fff;
}
.ele-box{
  border: 1px solid #bbb;
  height: 26px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px;
}
.no-mb-col .el-col{
  margin-bottom: 0px;
}
.sele-ele-box{
  height: 160px;
  padding: 20px;
  margin-top: 10px;;
}
</style>
