<template>
  <div class="wrap">
    <div class="btn">
      <div class="chunk">
        <el-button
          icon="el-icon-back"
          @click="
            $router.replace({ path: '/integrationOption/masterDataOptions' })
          "
        >返回
        </el-button
        >
      </div>
      <div class="chunk">
        <el-button
          icon="el-icon-first-aid-kit"
          type="primary"
          @click="saveHandle"
        >保存
        </el-button
        >
      </div>
    </div>
    <div class="main">
      <!--      <div class="btn">-->
      <!--        <el-button icon="el-icon-plus" type="primary" @click="addHandle">新增</el-button>-->
      <!--      </div>-->
      <baseTable @onFunc="onFunc" :tableData="tableData" :tabLoading="tabLoading"
                 :tableColumn="tableColumn" :funData="funData" :border="false">
        <template #appId="{row}">
          <baseNewSelect v-model="row['appId']" :itemObj="{label:'name',value:'id'}"
                         @seleChange="(val)=>seleChangeHanlde(val,row,'main')"></baseNewSelect>
        </template>
        <template #addApi="{row}">
          <div class="line" flex>
            <baseNewSelect v-model="row['addApi']" :itemObj="{label:'apiName',value:'id'}"
                           :appId="row['appId']" :flag="true"
                           @seleChange="(val)=>seleChangeHanlde(val,row,'addApi')"
            ></baseNewSelect>
            <el-button :disabled="!row['addApi']" @click="configurationHanlde(row,row['addApi'],'addApi')"
                       icon="el-icon-edit" type="primary"
            ></el-button>
          </div>

        </template>
        <template #deleteApi="{row}">
          <div class="line" flex>
            <baseNewSelect v-model="row['deleteApi']" :itemObj="{label:'apiName',value:'id'}"
                           :appId="row['appId']" :flag="true"
                           @seleChange="(val)=>seleChangeHanlde(val,row,'deleteApi')"
            ></baseNewSelect>
            <el-button :disabled="!row['deleteApi']" @click="configurationHanlde(row,row['deleteApi'],'deleteApi')"
                       icon="el-icon-edit" type="primary"></el-button>
          </div>

        </template>
      </baseTable>
      <div class="receiptsAddRow">
        <el-link
          type="primary"
          @click="addRowHandle"
          :underline="false"
        >+ 添加
        </el-link
        >
      </div>
    </div>
    <footer>
    </footer>
    <baseDialog v-model="addSwitch" @close="dialogCloseHandle" :width="dialogWidth" @confirm="confirmHandle">
      <div class="addBox" v-if="addSwitch">
        <div class="title">
          使用类型
        </div>
        <div class="radioList">
          <el-radio-group v-model="addType" @change="typeChangHandle">
            <el-radio label="1">使用插件</el-radio>
            <el-radio label="2">连线</el-radio>
          </el-radio-group>
        </div>
        <div class="content">
          <template v-show="addType==='1'">
            <div class="wrapContent" v-show="addType==='1'">
              <div class="chunk">
                <div class="label">使用插件</div>
                <div class="select">
                  <el-select v-model="plugIn" placeholder="请选择">
                    <el-option
                      v-for="item in options"
                      :key="item.pluginId"
                      :label="item.pluginLabel"
                      :value="item.pluginId">
                    </el-option>
                  </el-select>
                </div>
              </div>
            </div>
          </template>
          <template v-show="addType==='2'">
            <div class="wrapContent" v-show="addType==='2'">
              <div class="title">链接对照表</div>
              <div class="link">
                <div class="left">
                  <baseLink
                    v-loading="linkloading"
                    ref="link"
                    :lookFlag="lookFlag"
                    :leftData="linkData.leftData"
                    :rightData="linkData.rightData"
                    @linechange="getLineData"
                    :lineData="linkData.lineData"
                  ></baseLink>
                </div>
                <div class="right">
                  <div class="title">
                    <h1 style="font-size: 16px">连接结果</h1>
                  </div>
                  <div>
                    <div
                      v-for="item in linkData.lineData"
                      :key="item.leftid"
                      class="result"
                    >
                      <div class="left" :style="{ color: item.stroke }">
                        {{ item.leftTitle }}
                      </div>
                      <div class="middle">-</div>
                      <div class="right" :style="{ color: item.stroke }">
                        {{ item.rightTitle }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </baseDialog>
  </div>
</template>

<script>
import baseDialog from "@/views/integrationOption/compoments/baseDialog";
import BaseTable from "@/views/intergrationTask/compoments/baseTable.vue";
import baseNewForm from "@/views/intergrationTask/compoments/baseNewForm";
import {getApiModuleApi} from "@/api/apiChunks";
import {deepClone} from "@/utils/index.js";
import {getUserModuleApi} from "@/api/integrationOption/integrationOption";
import basePage from "@/views/intergrationTask/compoments/basePage.vue";
import baseLink from "./baseLink/index.vue"
import baseNewSelect from "./baseNewSelect.vue"

export default {
  data() {
    return {
      appOptions: [],
      addApiOptions: [],
      deleApiOptopns: [],
      options: [],//插件op
      plugIn: "",//插件
      addSwitch: false, //dialog
      tabLoading: false, // tableloading
      tableColumn: [ //table
        {
          title: "应用列表",
          id: "appId",
        },
        {
          title: "新增接口",
          id: "addApi",
        },
        {
          title: "删除接口",
          id: "deleteApi",
        },
      ],
      tableData: [], //table
      pageModel: { //page
        pageIndex: 1,
        total: 10,
        limit: 10,
      },
      funData: [ //table
        {text: "删除", color: "#e44b2d"}
      ],
      addType: "1", //使用类型
      linkloading: false, //linkloading
      lookFlag: false, //是否为查看模式
      linkData: { //连线组件数据
        leftData: [
          {label: 1, id: 1},
          {label: 1, id: 2},
          {label: 1, id: 3},
          {label: 1, id: 4},
          {label: 1, id: 5},
        ],
        leftDataCopy: [{label: 1, id: 1},
          {label: 1, id: 2},
          {label: 1, id: 3},
          {label: 1, id: 4},
          {label: 1, id: 5},],
        rightData: [{label: 1, id: 6},
          {label: 1, id: 7},
          {label: 1, id: 8},
          {label: 1, id: 9},
          {label: 1, id: 10},],
        rightDataCopy: [{label: 1, id: 6},
          {label: 1, id: 7},
          {label: 1, id: 8},
          {label: 1, id: 9},
          {label: 1, id: 10},],
        lineData: [],
      },
      dialogWidth: '40%',
      activedRow: {},
      activedType: "",
    };
  },
  methods: {
    onFunc(row) {
      this.tableData.splice(row.index, 1)
    },
    confirmHandle() {
      //addType、deleteType、addList、deleteList、addPlug、deletePlug
      if (this.addType === '1' && !this.plugIn) {
        this.$vmNews("请选择使用插件", "warning")
        return
      }
      if (this.addType === '2' && !this.linkData.lineData.length) {
        this.$vmNews("请配置链接对照表", "warning")
        return
      }

      if (this.activedType === 'addApi') {
        this.$set(this.activedRow, 'addType', this.addType)
        if (this.addType === '1') {
          this.$set(this.activedRow, 'addPlug', this.plugIn)
        } else {
          let arr = []
          this.linkData.lineData.forEach((item) => {
            //参考2 连线数据保存
            let tempObj = {};
            tempObj["sourceFeld"] = item["leftTitle"].split(".").slice(-1);
            tempObj["sourceName"] = item["leftTitle"];
            tempObj["sourcePath"] = item["leftTitle"];
            tempObj["targetField"] = item["rightTitle"].split(".").slice(-1);
            tempObj["targetPath"] = item["rightTitle"];
            tempObj["sourceFieldPath"] = JSON.stringify(item["leftidarr"]);
            tempObj["targetFieldPath"] = JSON.stringify(item["rightidarr"]);
            tempObj["coordinate"] = JSON.stringify(item);
            arr.push(tempObj);
          });
          this.$set(this.activedRow, 'addList', arr)
        }
      } else {
        this.$set(this.activedRow, 'deleteType', this.addType)
        if (this.addType === '1') {
          this.$set(this.activedRow, 'deletePlug', this.plugIn)
        } else {
          let arr = []
          this.linkData.lineData.forEach((item) => {
            //参考2 连线数据保存
            let tempObj = {};
            tempObj["sourceField"] = item["leftTitle"].split(".").slice(-1);
            tempObj["sourceName"] = item["leftTitle"];
            tempObj["sourcePath"] = item["leftTitle"];
            tempObj["targetField"] = item["rightTitle"].split(".").slice(-1);
            tempObj["targetPath"] = item["rightTitle"];
            tempObj["sourceFieldPath"] = JSON.stringify(item["leftidarr"]);
            tempObj["targetFieldPath"] = JSON.stringify(item["rightidarr"]);
            tempObj["coordinate"] = JSON.stringify(item);
            arr.push(tempObj);
          });
          this.$set(this.activedRow, 'deleteList', arr)
        }
      }
      console.log(this.activedRow)
      this.addSwitch = false
    },
    lineDataHandle(targetid, arr, saveName, saveId) {
      arr.some((item) => {
        if (item.id === targetid) {
          this.$set(item, "value", true);
          this.$set(item, "isline", true);
          this.$set(item, saveName, saveId);
          return true;
        } else if (item.children && item.children.length) {
          this.lineDataHandle(targetid, item.children, saveName, saveId);
          return false;
        }
      });
    },
    // 递归处理函数
    selectDataHanlde(resultArr, arr) {
      arr.forEach((item) => {
        let obj = {};
        resultArr.push(obj);
        obj["label"] = item.parameterName;
        obj["id"] = item.id;
        obj["type"] = item.concreteType;
        if (item.children) {
          obj["children"] = [];
          this.selectDataHanlde(obj["children"], item.children);
        }
      });
    },
    // 点击按钮配置事件 回显
    async configurationHanlde(row, val, key) {
      this.activedRow = row
      this.activedType = key
      let dist = {
        addApi: ['addType', 'addList', 'addPlug'],
        deleteApi: ['deleteType', 'deleteList', 'deletePlug']
      }
      this.addType = row[dist[key][0]] || "1"
      if (this.addType === '1') {
        this.plugIn = row[dist[key][2]]
      } else {
        this.dialogWidth = "90%"
      }
      const res = await getUserModuleApi({
        tl: "sysApplicationService",
        as: "application",
        dj: "debugAppApi"
      }, {
        id: val,
        appId: row['appId']
      })
      const res1 = await getApiModuleApi(
        {
          tl: "sysApplicationService",
          as: "application",
          dj: "debugAppApi",
        },
        {id: val, appId: row['appId']}
      );
      let tempArr = []
      let bodyIn = JSON.parse(res.attribute.api.bodyIn)
      if (bodyIn[0] && bodyIn[0].children) {
        this.selectDataHanlde(tempArr, bodyIn[0].children);
      }
      this.linkData.rightData = tempArr
      res1.attribute.para.forEach(item => {
        if (item.interfaceType === '2') {
          this.linkData.rightData.push({
            label: item.interfaceKey,
            id: item.id
          })
        }

      })
      if (row[dist[key][1]] && row[dist[key][1]].length) {
        this.linkData.lineData = []
        row[dist[key][1]].forEach(item => {
          //
          let leftArr = JSON.parse(item.sourceFieldPath);
          let saveId = leftArr[leftArr.length - 1];
          let rightArr = JSON.parse(item.targetFieldPath);
          let targetid = rightArr[rightArr.length - 1];
          this.lineDataHandle(
            targetid,
            this.linkData.rightData,
            "leftid",
            saveId
          );
          this.lineDataHandle(
            saveId,
            this.linkData.leftData,
            "rightid",
            targetid
          );
          console.log(item)
          if (item.coordinate) {
            this.linkData.lineData.push(JSON.parse(item.coordinate));
          }
        })

      }
      this.addSwitch = true
      this.$nextTick(() => {
        this.$refs.link.line = deepClone(this.linkData.lineData)
        this.$refs.link.resizeHeight();
      });
    },
    seleChangeHanlde(val, row, key) {
      let dist = {
        addApi: ['addType', 'addList', 'addPlug'],
        deleteApi: ['deleteType', 'deleteList', 'deletePlug']
      }

      if (key === 'main') {
        this.$set(row, "addApi", "")
        this.$set(row, "deleteApi", "")
      } else {
        console.log(key)
        this.$set(row, dist[key][0], "")
        this.$set(row, dist[key][1], [])
        this.$set(row, dist[key][2], "")
        console.log(row)
      }

    },
    addRowHandle() {
      this.tableData.push({})
    },
    async initSelect() {
      const plugRes = await getUserModuleApi({
        tl: "pluginService",
        as: "plugins",
        dj: "queryPluginsByType"
      }, {
        "pluginType": "1"
      })
      this.options = plugRes.attribute
    },
    async init() {
      const res = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "queryMdmModuleDistribute"
      }, {
        id: this.$route.query.id
      })
      console.log(res, 'init')
      if (res.status === '200') {
        this.tableData = res.attribute
      }
    },
    async initLeftLink() {
      const res = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "queryMdmShowAll"
      }, {id: this.$route.query.id})
      if (res.status === '200') {
        let arr = []
        res.attribute.forEach(item => {
          arr.push({
            label: item.name,
            id: item.id
          })
        })
        this.linkData.leftData = deepClone(arr)
        this.linkData.leftDataCopy = deepClone(arr)
      }
    },
    //使用类型变更事件
    typeChangHandle(val) {
      if (val == 2) {
        this.dialogWidth = '95%'
        this.$nextTick(() => {
          this.$refs.link.resizeHeight();
        });
      } else {
        this.dialogWidth = '40%'
      }
    },
    // dialog关闭事件
    dialogCloseHandle() {
      //重置连线组件数据
      this.linkData.lineData = [];
      this.linkData.leftData = deepClone(this.linkData.leftDataCopy);
      this.linkData.rightData = []
      //重置radio选择
      this.addType = "1";
      //重置select选择
      this.plugIn = "";
      //宽度默认
      this.dialogWidth = '40%'
    },
    // 获取连线数据 x y坐标等等
    getLineData(data) {
      this.linkData.lineData = deepClone(data);
    },
    // 页码
    currentChangeHandle(pageModel) {
      this.pageModel = pageModel;
      this.$nextTick(() => {
      });
    },
    // save
    async saveHandle() {
      let arr = []
      let flag = this.tableData.some((item, index) => {
        if (!item.appId) {
          this.$vmNews("请选择应用", "warning")
          return true
        }
        if (arr.includes(item.appId)) {
          this.$vmNews("不允许重复选择应用", "warning")
          return true
        }
        arr.push(item.appId)
        if (!item.addApi || !item.deleteApi) {
          this.$vmNews("请选择接口", "warning")
          return true
        }
        if (item.addApi === item.deleteApi) {
          this.$vmNews("新增接口和删除接口不能选同一个", "warning")
          return true
        }
        if (!item.addType) {
          this.$vmNews(`请配置${index + 1}行新增接口`, "warning")
          return true
        }
        if (!item.deleteType) {
          this.$vmNews(`请配置${index + 1}行删除接口`, "warning")
          return true
        }
      })
      if (flag) return
      let params = {
        id: this.$route.query.id,
        mdmModuleDistributeEntities: this.tableData,
      }
      const res = await getUserModuleApi({
        tl: "mdmService",
        as: "mdmService",
        dj: "doSaveMdmModuleDistribute",
      }, params)
      if (res.status === '200') {
        this.$vmNews("保存成功", "success")
        this.init()
      }
    },
    //add
    addHandle() {
      this.addSwitch = true
    }
  },
  components: {
    baseNewForm,
    BaseTable,
    baseDialog,
    baseNewSelect,
    basePage,
    baseLink
  },
  created() {
    this.init()
    this.initSelect()
    this.initLeftLink()
    this.$emit("flashActive", 4)
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-button {
  border-radius: 16px;
}

::v-deep .el-form-item {
  display: block !important;
}

.checkChunk {
  display: flex;
  flex-wrap: wrap;
}

.wrap {
  background-color: #fbfbfb;
  width: 100%;
  overflow: auto;

  > .btn {
    display: flex;
    justify-content: flex-end;

    > .chunk {
      margin-left: 10px;
    }
  }

  > .main {
    margin-top: 10px;
    background: #fff;
    padding: 20px;
    border-radius: 8px;

    .btn {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;
    }
  }

}

footer {
  margin-top: 20px;
}

.addBox {
  .title {
    font-weight: 600;
    margin: 10px 0;
  }

  .radioList {
    margin-top: 20px;
  }

  .content {
    margin-top: 30px;

    .chunk {
      display: flex;
      align-items: center;

      .label {
        font-weight: 800;
        margin-right: 10px;
      }
    }
  }

  .link {
    padding: 30px;
    display: flex;
    width: 100%;

    > .left {
      width: 1000px;
      min-height: 300px;
    }

    > .right {
      margin-left: 50px;
      width: 30vw;
      overflow: hidden;

      .result {
        margin-top: 30px;
        display: flex;
        justify-content: space-between;

        > .left {
          padding: 0 10px;
        }

        > .right {
          padding: 0 10px;
        }
      }
    }
  }
}

.receiptsAddRow {
  margin-top: 30px;
  border: 1px dotted #ccc;
  text-align: center;
  height: 50px;
  line-height: 50px;
}

.line {
  display: flex;
  justify-content: center;
}
</style>
