<template>
	<div class="xd-select-pages-path">
		<div class="xd-select-pages-path__input" :class="{'input-new':mode ==='new'}">
			<el-input
				v-model="path"
				:placeholder="placeholder"
				:disabled="inputDisabled"
				:size="size"
				clearable
        @input="handleConfirm"
        @clear="handleInputClear"
			></el-input>
			<el-button :size="size" @click="handleOpen" :disabled="inputDisabled" type="primary">预览</el-button>
		</div>
		<xd-dialog
			:title="title"
			:width="width"
			:show.sync="show"
			v-if="show"
			@onClose="handleClear"
		>
			<div class="xd-select-pages-path__path">
				<div class="xd-select-pages-path__path-tab" v-if="tabsList.length >1">
					<template v-for="(item,index) in tabsList">
						<div class="self" v-if="index === 0 && item.value ==='0' && tabsList.length > 1">当前模版</div>
						<div
              class="xd-select-pages-path__path-tab-item"
							:class="{
                active: index === tabsFirst,
                hasRoot: item.value ==='0' && tabsList.length > 1,
                iconH5: item['css'] === 'iconH5',
                iconWXMP: item['css'] === 'iconWXMP'
              }"
							@click="handleTabsFirst(index)"
              v-if="isOtherApp || (index === 0 && item.value ==='0')"
						>{{item.label}}</div>
						<div class="other"  v-if="index === 0 && item.value ==='0' && tabsList.length > 1 && isOtherApp">其他应用</div>
					</template>
				</div>
        <div
          v-if="hasContentList"
          class="xd-select-pages-path__path-content"
          :class="{noBorder: tabsList.length <=1}"
          :key="contentRefresh"
        >
          <el-tabs v-model="tabsChildren" @tab-click="handleClickTab">
            <el-tab-pane
              v-for="(cItem,cIndex) in contentList"
              :key="cIndex"
              :label="cItem.label"
              :name="cItem.value"
            >
              <div
                style="margin: 0 0 10px; background: wheat; padding: 8px;  font-size: 12px"
                v-if="tabsList[tabsFirst].value !== '0'"
              >
                <span>温馨提示：</span>
                <span style="color:red;">当模版被发布为H5应用时，选择链接为微信小程序应用路径时，将在前台不显示</span>
              </div>
              <div class="path-content" v-if="hasContentList">
                <template v-for="routers in lastTree(cItem.children)">
                  <h6>{{routers.label}}</h6>
                  <div>
                    <template v-for="router in routers.children">
                      <el-button
                        size="small"
                        :type="selectItemPath === router.value ? 'primary': ''"
                        @click="handleSelectRouter(router)"
                      >{{router.label}}</el-button>
                    </template>
                  </div>
                </template>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="xd-select-pages-path__path-content" v-else-if="this.tabsList[this.tabsFirst] && this.tabsList[this.tabsFirst].value === '0'">
          <xd-no-data height="350">当前模版暂无页面配置</xd-no-data>
        </div>
			</div>
			<template slot="btn">
				<el-button :size="size" @click="handleClear">取 消</el-button>
				<el-button :size="size" :disabled="!selectItemPath" type="primary" @click="handleConfirm">确 定</el-button>
			</template>
		</xd-dialog>
	</div>
</template>

<script>
  import emitter from 'element-ui/src/mixins/emitter';
  import XdDialog from "@/components/XdDialog";
  import XdNoData from "@/components/XdNoData";
  import {Loading} from 'element-ui';

  export default {
    name: "XdSelectPagesPath",
		components: {
      XdDialog,
      XdNoData
		},
    mixins: [emitter],
		props:{
      defaultValue: {
        type: Object | null,
        default() {
          return null
        },
      },

      maps: {
        type: Object | null,
        default() {
          return null
        },
      },

      setting: {
        type: Object,
        default() {
          return {}
        },
      },

      disabled: {
        type: Boolean,
        default: false,
      },

      size: {
        type: String,
        default: 'medium', //medium / small / mini
      },

      placeholder: {
        type: String,
        default: '请选择路径'
      },

      required: {
        type: Boolean,
        default: false,
      },

      //是否启用自定义校验器
      useCustomRules: {
        type: Boolean,
        default: false,
      },

      //数字字符串 转 数字
      isNumber: {
        type: Boolean,
        default: true,
      },

      //自定义方法
      handleCustom: {
        type: Function || null,
        default: null
      },

		},
		computed:{
      contentList() {
        if (this.tabsList === 0){
          return [];
				}
				else{
				  if(this.tabsList[this.tabsFirst].children.length === 0) {
            return [];
					}
				  this.tabsChildren = this.tabsList[this.tabsFirst].children[0].value;
				  return this.tabsList[this.tabsFirst].children;
				}
      },
      hasContentList(){
        return this.tabsList[this.tabsFirst].children.length > 0
			}
		},
		data(){
      return {
        path: '',//值
				pathItem: null,//
        timer:null,

				//dialog
        width: '900px',
				show: false,
        title: '请选择链接地址',
				inputDisabled: false,

				//tabs
				tabsFirst: 0,
				tabsChildren: 0,
				tabsList: [],
				selectItemPath: null,
        selectItem : null,
        contentRefresh: 'contentRefresh',

        isOtherApp: true,  //是否显示其他应用
        mode: 'old',
			}
		},

		created(){

      if (this.$xdHelper.checkVarType(this.disabled) === 'boolean'){
        this.inputDisabled = this.disabled;
			}

      //是否显示其他应用
      if(this.setting && this.$xdHelper.checkVarType(this.setting.isOtherApp) === 'boolean'){
        this.isOtherApp = this.setting.isOtherApp;
      }

      if (this.$xdHelper.checkVarType(this.setting.mode) === 'string'
        && ['old','new'].includes(this.setting.mode)
      ){
        this.mode = this.setting.mode;
      }

      if(this.$xdHelper.checkVarType(this.defaultValue) === 'object') {
        this.pathItem = this.$xdHelper.cloneDeep(this.defaultValue);
        this.path = this.pathItem.frontPath || this.pathItem.value;
        this.update();
        return
			}

      if(this.defaultValue &&
				this.$xdHelper.checkVarType(this.defaultValue) === 'string'
			) {
        this.pathItem = {
          "label": "''",
          "value": this.defaultValue,
          "parentId": 'this.defaultValue',
          "parentName": "",
          "path": "this.defaultValue",
          "dir": "",
          "appName": "当前模版路径",
          "appValue": "0",
          "aopen_app_code": "",
          "frontPath": this.defaultValue
        };
        this.path = this.pathItem.frontPath || this.pathItem.value;
        this.update();
			}

		},

		methods: {

      lastTree(tree) {
        let temp = {};
        tree.map(item=>{
        	if(!temp[item.parentId]) {
            temp[item.parentId] = {
              label: item.parentName,
              value: item.parentId,
              children: [item]
            }
					}
        	else{
            temp[item.parentId].children.push(item);
					}
				});
        return Object.keys(temp).map(key=>{
				  return temp[key];
				})
      },

      //==dialog==============
			handleTabsFirst(index){
			  this.tabsFirst = index;
			  this.tabsChildren = 0;
			  this.contentRefresh = this.$xdHelper.randomChar(20);
        this.selectItemPath = null;
        this.selectItem = null;
			},

			handleOpen(){

			  //数据模式
        if (this.setting['router']
        	&& this.$xdHelper.checkVarType(this.setting['router']) === 'array'
        ) {
          this.tabsList = this.setting['router'];
          this.show = true;
          this.tabsChildren = this.tabsList[this.tabsFirst].children[0].value;
				}

        //方法模式
        if (this.setting['router']
          && this.$xdHelper.checkVarType(this.setting['router']) === 'function'
        ) {
          let loading = Loading.service({});
          this.setting['router']({})
						.then(res=>{
              this.tabsList = res;
              this.show = true;
              this.tabsChildren = this.tabsList[this.tabsFirst].children[0].value;
						  console.log('reloadBoradData.fn',res)
              loading.close();
						})
						.catch(error=>{
              loading.close();
						})
				}

			},

			handleClear(){
        this.show = false;
        this.tabsFirst = 0;
        this.tabsChildren = 0;
        this.selectItemPath = null;
        this.selectItem = null;
			},

      handleInputClear(){
        this.selectItemPath = null;
        this.selectItem = null;
        this.pathItem = '';
        this.path = '';
        if(this.timer){
          clearTimeout(this.timer);
          this.timer = null
        }
        this.change();
        this.update();
      },

      handleConfirm(){
        this.timer = setTimeout(()=>{
          this.path = this.selectItemPath;
          let pathItem = this.$xdHelper.cloneDeep(this.selectItem);
          if(pathItem.appValue) pathItem.appValue = Number(pathItem.appValue);
          let platform_type = pathItem.platform_type
          if(pathItem.appType !== '') {
            if(!pathItem.platform_type) {
              platform_type = pathItem.appType === 'h5'? 9 : (pathItem.appType==='wxmp' ? 8:-1)
            }
          }
          pathItem['platform_type'] = platform_type;
          this.pathItem = pathItem;
          this.handleClear();
          this.change();
          this.update();
        },100)
			},

      handleSelectRouter(item){
			  if(item.value === this.selectItemPath) return;
        this.selectItemPath = item.frontPath;
        this.selectItem = item;
			},

      handleClickTab(){
        this.selectItemPath = null;
        this.selectItem = null;
			},
      //==dialog==============


      /**
			 * @description 需要校验检查参数是正确处理方法
       */
			checkParams(){
   			return this.pathItem;
			},

			/**
			 * @description 数据改变事件
			 */
			change(){
			  this.$emit('onChange', this.checkParams())
			},

      /**
			 * @description 双向绑定数据处理
       */
			update(){
        this.$emit('input', this.checkParams());
        if (this.$parent.$options['componentName'] === 'ElFormItem') {
          this.dispatch('ElFormItem', 'el.form.change', [this.checkParams()]);
          //this.dispatch('ElFormItem', 'el.form.blur', [this.checkParams()])
        }
			},


		}
  }
</script>

<style scoped lang="scss">
	.xd-select-pages-path {
		min-width: 290px;
		&__input {
			display: flex;
			justify-content: flex-start;
			align-items: center;

			& > *:first-child {
				max-width: 60%;
				flex-shrink: 0;
				margin-right: 10px;
			}
		}

    .input-new {
      & > *:first-child {
        max-width: none;
        flex: 1;
      }
      & > *:last-child {
        flex-shrink: 0;
      }
    }

		&__path {
			display: flex;
			justify-content: flex-start;
			align-items: flex-start;
      height: 500px;

			&-tab {
				width: 210px;
				flex-shrink: 0;
				overflow-y: auto;
				overflow-x: hidden;
				padding: 10px 0;
        max-height: 480px;

				.self,.other {
					line-height: 36px;
					text-align: center;
					font-size: 16px;
					color: #333;
					margin: 10px 15px 10px 0;
					background: #f6f6f6;
					font-weight: 900;
				}


				&-item {
					margin-top: 0;
					margin-bottom: 12px;
					text-align: left;
					margin-right: 15px;
					border:1px solid #e5e5e5;
					line-height: 15px;
					padding: 10px 5px 10px 30px;
					font-size: 14px;
					color:#333;
					cursor: pointer;
					border-radius: 4px;

          &.iconH5 {
            background: url("//img.jufubao.cn/common/h5-20.png?v1") no-repeat 5px center;
          }
          &.iconWXMP {
            background: url("//img.jufubao.cn/common/mp-20.png?v2") no-repeat 5px center;
          }

					&.hasRoot {
						margin-bottom: 0;
					}

					&.active {
						border: 1px solid $blue;
						background-color: $blue;
						color: #fff;
					}

					&:last-child {
						margin-bottom: 0;
					}
					& > *  {
						width: 80%;
					}
				}

			}

			&-content {
				flex: 1;
				height: 450px;
				padding: 0 0 10px 15px;

        & ::v-deep .el-tabs__content {
          height: 400px;
          overflow-y: auto;
        }

				&.noBorder {
					border-left: 0
				}
			}
		}

	}

	.path-content {
		& > h6 {
			padding: 0 0 0px;
			margin: 0;
			font-size: 14px;
			color: #000;
			font-weight: bold;
		}
		& > div {
			padding: 10px 0;
			& > * {
				margin: 0 10px 10px 0;
			}
		}

	}

	@media screen and (max-width: 768px) {
		.xd-select-pages-path {
			overflow-x: auto;
			max-width: 290px;
			min-width: 220px;
			padding-bottom: 10px;
			&__input {
				flex-flow: nowrap;

				& > * {
					flex-shrink: 0;

				}
			}
		}
	}
</style>
