<style>
.webSiteBg {
  padding: 20px;
  background-color: #fff;
  height: 100%;
}
.WebSiteSearch .el-tabs__content {
  height: calc(100% - 55px);
}
</style>
<template>
  <!--网站设定(网站设置)-->
  <div class="WebSiteSearch" style="height:100%">
    <el-form :model="PostMsg" ref="PostMsg" label-width="130px" style="height:100%">
      <el-tabs v-model="activeName" style="height:100%;">
        <el-tab-pane :label="$t('objFill.v101.jibenshedin')" name="first">
          <div class="webSiteBg">
            <el-row>
              <el-col :span="8">
                <el-form-item label="顯示標題">
                  <el-input v-model="PostMsg.ShowTitle"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="編輯熱門關鍵字">
                  <el-input v-model="keywords" @keyup.native.enter="addKeyWords">
                    <el-button slot="append" @click="addKeyWords()">{{$t('pub.addBtn')}}</el-button>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item>
                  <el-tag
                    v-for="(tag,index) in keyWordsArr"
                    :key="tag"
                    closable
                    :type="tag"
                    @close="closeTag(index)"
                    style="margin-right:10px;"
                  >{{tag}}</el-tag>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item>
                  <el-button type="primary" size="small" @click="saveData()">{{$t('objFill.v101.cunchuxiug')}}</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="地區" name="second">
          <div class="webSiteBg">
            <el-row>
              <el-checkbox-group v-model="SearchAreaArr">
                <el-col
                  :span="6"
                  v-for="(item,index) in areaData"
                  :key="index"
                  style="margin-bottom:20px;"
                >
                  <el-checkbox :label="item.Id" :key="item.AreaName">{{item.AreaName}}</el-checkbox>
                </el-col>
              </el-checkbox-group>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-button
                  type="primary"
                  size="small"
                  style="margin:40px 0"
                  @click="saveData()"
                >{{$t('objFill.v101.cunchuxiug')}}</el-button>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="供應商旅行社" name="third" style="height:100%">
          <div class="webSiteBg">
            <!-- <el-button :disabled="chooseTAArray.length>0?false:true" @click="setTravelagencyArea(1)" style="padding-bottom:10px;">批次設定區域</el-button> -->
            <el-table
              v-loading="isLoadingAgentArea"
              ref="multipleTable"
              :data="PostMsg.TravelagencyList"
              tooltip-effect="dark"
              style="width: 100%;height:calc(100% - 50px);overflow-y:auto;"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="100px"></el-table-column>
              <el-table-column prop="IsOpenSearch" label="開放搜尋" width="100px">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.IsOpenSearch"
                    :active-value="1"
                    :inactive-value="0"
                    active-color="#13ce66"
                    inactive-color="#dcdfe6"
                    :disabled="scope.row.SyncStatus==0"
                  ></el-switch>
                </template>
              </el-table-column>
              <el-table-column prop="AgencyName" :label="$t('objFill.v101.lvxingshe')" width="300px"></el-table-column>
              <el-table-column label="設定區域" width="200px">
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.row.SyncStatus==1"
                    type="primary"
                    size="small"
                    @click="getAgentArea(scope.row)"
                  >設定</el-button>
                  <span v-else style="color:#f45c43;">正在接入,敬請期待</span>
                </template>
              </el-table-column>
              <el-table-column prop="SetArea" label="開放區域">
                <template slot-scope="scope">{{getAreaName(scope.row.SetArea)}}</template>
              </el-table-column>
            </el-table>
            <el-button type="primary" size="small" style="margin-top:20px;" @click="saveData()">{{$t('objFill.v101.cunchuxiug')}}</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="搜尋結果頁面" name="fourth">
          <div class="webSiteBg">
            <el-row>
              <el-col :span="8">
                <el-form-item label="顯示類型">
                  <el-select v-model="PostMsg.ShowType" style="width:100%">
                    <el-option label="豆腐格" :value="0" :key="0"></el-option>
                    <el-option label="篩選式列表" :value="1" :key="1"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    size="small"
                    style="margin:40px 0"
                    @click="saveData()"
                  >{{$t('objFill.v101.cunchuxiug')}}</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <el-dialog custom-class="w450" title="設定區域" :visible.sync="outerVisible" center>
      <el-row>
        <el-checkbox-group v-model="taAreaArr">
          <el-col
            :span="6"
            v-for="(item,index) in areaData"
            :key="index"
            style="margin-bottom:20px;"
          >
            <el-checkbox :label="item.Id" :key="item.AreaName">{{item.AreaName}}</el-checkbox>
          </el-col>
        </el-checkbox-group>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <button class="hollowFixedBtn" @click="closeArea()">{{$t('pub.cancelBtn')}}</button>
        <button class="normalBtn" @click="sureTAArea()">{{$t('pub.sureBtn')}}</button>
      </div>
    </el-dialog>
    <el-dialog custom-class="w450" title="選擇您需要的區域" :visible.sync="showAgentArea" center>
      <transition name="el-zoom-in-top">
        <el-row v-show="chosenStep==0">
          <el-checkbox-group v-model="agentChosenArea">
            <el-col
              :span="6"
              v-for="(item,index) in agentArea"
              :key="index"
              style="margin-bottom:20px;"
            >
              <el-checkbox :label="item" :key="item.AreaName">{{item.AreaName}}</el-checkbox>
            </el-col>
          </el-checkbox-group>
        </el-row>
      </transition>
      <transition name="el-zoom-in-bottom">
        <el-row v-show="chosenStep==1">
          <el-row style="margin-bottom:10px;">
            <el-col :span="10" style="font-size:16px;color:#33B3FF">{{agentName}}</el-col>
            <el-col :span="4">&nbsp;</el-col>
            <el-col :span="10" style="font-size:16px;color:#33B3FF">您的分區</el-col>
          </el-row>
          <el-row type="flex" style="margin-bottom:10px;" align="middle" v-for="(x,i) in agentChosenArea" :key="i">
            <el-col :span="10" style="font-size:14px">{{x.AreaName}}</el-col>
            <el-col :span="4" style="color:#ccc;">
              <i style="font-size:16px;" class="iconfont icon-gengduojiantou"></i>
            </el-col>
            <el-col :span="10" style="font-size:12px">
              <el-select v-model="x.targetId" filterable :placeholder="$t('pub.pleaseSel')" @change="changeMapping">
                <el-option
                  v-for="(y,yi) in areaData"
                  :key="yi"
                  :label="y.AreaName"
                  :value="`${y.Id}_${i}`">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-row>
      </transition>
      <div slot="footer" class="dialog-footer">
        <button class="hollowFixedBtn" @click="closeArea()">{{$t('pub.cancelBtn')}}</button>
        <button class="hollowFixedBtn" @click="goPrevSetup" v-if="chosenStep==1">上一步</button>
        <button class="normalBtn" @click="sureAgentArea()">{{chosenStep==0?"下一步":"完成"}}</button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //是否显示弹窗
      outerVisible: false,
      //选项卡
      activeName: "first",
      //关键字
      keywords: "",
      keyWordsArr: [], //关键字数组
      PostMsg: {
        Id: 0,
        ShowTitle: "",
        HotWords: "",
        SearchAreaIds: "",
        ShowType: 0,
        TravelagencyList: [],
      },
      //地区数据
      areaData: [],
      //总数据
      dataList: [],
      //选中的地区
      SearchAreaArr: [],
      //选中的旅行社
      chooseTAArray: [],
      //旅行社区域
      taAreaArr: [],
      agentArea:[],
      isLoadingAgentArea:false,
      showAgentArea:false,
      agentChosenArea:[],
      chosenStep:0,
      agentName:"",
      isPreOpenSearch:false,
      chosenAgentId:0
    };
  },
  mounted() {
    this.getData();
    this.getAreaList();
  },
  methods: {
    //获取配置
    getData() {
      this.apipost(
        "ws_get_GetSearchConfig",
        {},
        (res) => {
          if (res.data.resultCode == 1) {
            var tempData = res.data.data;
            if (tempData) {
              if (tempData.Id) {
                this.PostMsg.Id = tempData.Id;
              }
              if (tempData.ShowTitle) {
                this.PostMsg.ShowTitle = tempData.ShowTitle;
              }
              if (tempData.HotWords) {
                this.PostMsg.HotWords = tempData.HotWords;
              }
              if (tempData.HotWordsList && tempData.HotWordsList.length > 0) {
                this.keyWordsArr = tempData.HotWordsList;
              }
              if (tempData.SearchAreaIds) {
                this.PostMsg.SearchAreaIds = tempData.SearchAreaIds;
              }
              if (
                tempData.SearchAreaIdsList &&
                tempData.SearchAreaIdsList.length > 0
              ) {
                this.SearchAreaArr = tempData.SearchAreaIdsList;
              }
              if (tempData.ShowType) {
                this.PostMsg.ShowType = tempData.ShowType;
              }
              if (tempData.TravelagencyList) {
                this.PostMsg.TravelagencyList = tempData.TravelagencyList;
              }
            }
            this.$forceUpdate()
          } else {
            this.Error(res.data.message);
          }
        },
        (err) => {}
      );
    },
    getCheckStatus(id){
      return this.agentChosenArea.findIndex(x=>x.Id==id)!=-1
    },
    goPrevSetup(){
      this.chosenStep=0
    },
    changeMapping(d){
      if(d){
        let t=d.split('_')
        this.agentChosenArea[t[1]].targetId=d
        this.$forceUpdate()
      }
    },
    sureAgentArea(){
      if(this.chosenStep==0 && this.agentChosenArea.length>0){
        this.agentChosenArea.forEach(x=>{
          x.targetId=x.targetId?x.targetId:''
        })
        this.chosenStep=1
      } else if(this.chosenStep==0 && this.agentChosenArea.length==0){
        this.Error("請選擇您需要使用的區域");
      } else if(this.chosenStep==1 && this.agentChosenArea.length>0){
        let errorMsg=""
        let msg={
          SetArea:[]
        };
        this.agentChosenArea.forEach(x=>{
          if(x.targetId!=''){
            msg.SetArea.push({
              "agentAreaId":x.Id,
              "agentAreaName":x.AreaName,
              "targetId":x.targetId.split('_')[0]
            });
          }else{
            errorMsg="請選擇對應分區"
          }
        })
        if(errorMsg==""){
          msg.IsOpenSearch=this.isPreOpenSearch?1:0
          msg.AgencyId=this.chosenAgentId
          msg.SetArea=JSON.stringify(msg.SetArea)
          this.apipost("ws_set_agentarea", msg, (res) => {
            if(res.data.resultCode==1){
              this.closeArea()
              this.getData()
            }else{
              this.Error("設置失敗,請嘗試刷新頁面");
            }
            this.isLoadingAgentArea=false
          });
        }else{
          this.Error(errorMsg);
        }
      }
    },
    getAgentArea(row) {
      this.isLoadingAgentArea=true
      let msg = { 'agentid':row.AgencyId };
      this.apipost("ws_get_getagent_areafirstlevel", msg, (res) => {
        if(res.data.resultCode==1){
          this.agentArea=res.data.data
          this.agentChosenArea=[]
          this.formatChosenInit(row)
          this.showAgentArea=true
          this.chosenStep=0
          this.agentName=row.AgencyName
          this.chosenAgentId=row.AgencyId
        }else{
          this.Error("加載失敗,請嘗試刷新頁面");
        }
        this.isLoadingAgentArea=false
      });
    },
    formatChosenInit(row){
      if(row.SetArea){
        try {
          let area=JSON.parse(row.SetArea)
          if(area.length>0){
            this.agentChosenArea=this.agentArea.filter(x=>{
              let t=area.find(n=>n.agentAreaId==x.Id)
              if(t){
                x.targetId=t.targetId
                return x
              }
              return false
            })
            this.agentChosenArea.forEach((x,i)=>{
              x.targetId= x.targetId+"_"+i
            })
          }
        } catch (error) {}
      }
    },
    //保存数据
    saveData() {
      //区域
      var tempSearchAreaIds = "";
      if (this.SearchAreaArr && this.SearchAreaArr.length > 0) {
        this.SearchAreaArr.forEach((item) => {
          tempSearchAreaIds += item + ",";
        });
        this.PostMsg.SearchAreaIds = tempSearchAreaIds.substr(
          0,
          tempSearchAreaIds.length - 1
        );
      } else {
        this.PostMsg.SearchAreaIds = tempSearchAreaIds;
      }
      //热门关键词
      var tempHotWords = "";
      if (this.keyWordsArr && this.keyWordsArr.length > 0) {
        this.keyWordsArr.forEach((item) => {
          tempHotWords += item + ",";
        });
        this.PostMsg.HotWords = tempHotWords.substr(0, tempHotWords.length - 1);
      } else {
        this.PostMsg.HotWords = tempHotWords;
      }
      this.apipost(
        "ws_post_SetSearchConfig",
        this.PostMsg,
        (res) => {
          if (res.data.resultCode == 1) {
            this.getData();
            this.Success(res.data.message);
          } else {
            this.Error(res.data.message);
          }
        },
        (err) => {}
      );
    },
    //获取地区
    getAreaList() {
      this.apipost(
        "ws_get_GetRootArea",
        {},
        (res) => {
          if (res.data.resultCode == 1) {
            this.areaData = res.data.data;
          } else {
            this.Error(res.data.message);
          }
        },
        (err) => {}
      );
    },
    //关闭标签
    closeTag(index) {
      this.keyWordsArr.splice(index, 1);
    },
    //多选
    handleSelectionChange(val) {
      this.chooseTAArray = JSON.parse(JSON.stringify(val));
    },
    //返回地区名称
    getAreaName(areaIds) {
      var nameStr = "";
      try{
        var t=JSON.parse(areaIds)
        if(t && t.length>0){
          t.forEach(x=>{
            nameStr += x.agentAreaName + "、";
          })
        }
      }catch(e){}
      // if (areaIds) {
      //   var tempArray = areaIds.split(",");
      //   if (tempArray && tempArray.length > 0) {
      //     tempArray.forEach((item) => {
      //       var areaItem = this.areaData.find((member) => {
      //         return member.Id == item;
      //       });
      //       if (areaItem) {
      //         nameStr += areaItem.AreaName + "、";
      //       }
      //     });
      //   }
      // }
      // if (nameStr && nameStr.length > 0) {
      //   nameStr = nameStr.substr(0, nameStr.length - 1);
      // }

      return nameStr;
    },
    //设置旅行区域
    setTravelagencyArea(type, item) {
      this.taAreaArr = [];
      if (type == 1) {
        if (this.chooseTAArray && this.chooseTAArray.length > 0) {
          this.outerVisible = true;
          this.chooseTAArray.forEach((subItem) => {
            var tempArray = subItem.SetArea.split(",");
            if (tempArray && tempArray.length > 0) {
              tempArray.forEach((sItem) => {
                //数组里面不存在
                if (this.taAreaArr.indexOf(Number(sItem)) == -1) {
                  this.taAreaArr.push(Number(sItem));
                }
              });
            }
          });
        } else {
          this.Info("请选择要设置的旅行社!");
        }
      } else {
        this.outerVisible = true;
        if (item) {
          if (item.SetArea) {
            var tempArray = item.SetArea.split(",");
            if (tempArray && tempArray.length > 0) {
              tempArray.forEach((sItem) => {
                this.taAreaArr.push(Number(sItem));
              });
            }
          }
          this.chooseTAArray.push(item);
        }
      }
    },
    //新增关键字
    addKeyWords() {
      if (this.keywords != "") {
        this.keyWordsArr.push(this.keywords);
        this.keywords = "";
      }
    },
    //关闭弹窗
    closeArea() {
      this.outerVisible = false;
      this.showAgentArea=false;
    },
    //选中区域确定
    sureTAArea() {
      var tempAreaIds = "";
      if (this.taAreaArr && this.taAreaArr.length > 0) {
        this.taAreaArr.sort().forEach((item) => {
          tempAreaIds += item + ",";
        });
        if (tempAreaIds && tempAreaIds.length > 0) {
          tempAreaIds = tempAreaIds.substr(0, tempAreaIds.length - 1);
        }
      }
      if (this.chooseTAArray && this.chooseTAArray.length > 0) {
        var jsonData = JSON.parse(JSON.stringify(this.chooseTAArray));
        var that = this;
        jsonData.forEach((item) => {
          that.PostMsg.TravelagencyList.forEach((subItem) => {
            if (item.AgencyId == subItem.AgencyId) {
              subItem.SetArea = tempAreaIds;
            }
          });
        });
        this.chooseTAArray = [];
        this.taAreaArr = [];
      }
      this.outerVisible = false;
    },
  },
};
</script>