<template>
  <div class="app-container">
    <div class="app-container__item">
      <div class="app-container__item-body">
        <el-button @click="handleClick" type="primary" :disabled="selectData.length === 0">生成配置文件</el-button>
        <xd-base-dynamic-field
          label-width="0"
          ref="mainForm"
          v-model="formMainValue"
          :list="formMainList"
          size="medium"
          @success="handleSuccess"
          @onApiSuccessUrl="handleApiSuccessUrl"
          @onGetParamsAndHeader="handleGetParamsAndHeader"
        >
          <div slot="MAIN" slot-scope="scope" style="padding: 20px 0">
            <div class="xd-list">
              <div class="xd-list__item" v-for="item in formListTest" :key="item.id">
                <div class="xd-list__item-title" v-html="`${item.id}、${item.label}`"></div>
                <div class="xd-list__item-content">
                  <div>
                    <div
                      class="app-container__item-body-value"
                      v-if="item.key !== 'slot' && item.key !== 'title' &&  item.key !== 'el-html' && item.model !== null"
                    >
                      <xd-json-view :data="item.model"></xd-json-view>
                    </div>
                    <xd-base-dynamic-field
                      v-model="item.model"
                      :label-width="scope.width"
                      :list="[item.value]"
                      size="medium"
                      @success="handleSuccess"
                      @onApiSuccessUrl="handleApiSuccessUrl"
                      @onGetParamsAndHeader="handleGetParamsAndHeader"
                    >
                    </xd-base-dynamic-field>
                  </div>
                  <div><el-button type="primary" @click="handleAddClick(item)">添加</el-button></div>
                </div>
              </div>
            </div>
          </div>
        </xd-base-dynamic-field>
        <el-button @click="handleClick" type="primary" :disabled="selectData.length===0">生成配置文件</el-button>
      </div>
    </div>
    <div class="xd-dialog">
      <div class="xd-dialog-btn">
        <el-button @click="handleClick" type="primary" size="small" :disabled="selectData.length===0">生成配置文件</el-button>
      </div>
      <div class="xd-dialog-title">
        <i class="el-icon-arrow-down" v-if="!show" @click="handleShow(true)"></i>
        <i class="el-icon-arrow-up" v-if="show" @click="handleShow(false)"></i>
      </div>
      <div class="xd-dialog-content" :style="{maxHeight: show ? '150px': '300px'}">
        <xd-table
          :key="tableRefresh"
          is-border
          size="mini"
          :headers="headers"
          :list="selectData"
          @onClick="handleTableClick"
        ></xd-table>
      </div>
    </div>
<!--    <codemirror v-model="OssSortListImageCode" :options="editorOptions"></codemirror>-->
  </div>
</template>

<script>
  import XdJsonView from "@/components/XdJsonView";
  import XdSearch from "@/components/XdSearch";
  import XdBaseDynamicField from "@/components/XdBaseDynamicField";
  import XdTable from "@/components/XdTable";
  import {genUpToken} from './../scripts/qiniu'
  import setting from "./setting";
  import cityData from './cityData';
  import testData from './testData';
  import download from 'downloadjs';
  const beautify = require('js-beautify');
  
  import {
    getCodemirror,
    getMirrorIOptions
  } from './mirror'
  
  


  export default {
    name: 'AppForm',
    components: {
      XdBaseDynamicField,
      XdSearch,
      XdJsonView,
      XdTable,
      codemirror: getCodemirror()
    },
    data() {
      return {
        headers: [
          {type: 'index'},
          {type: 'normal', prop: 'id', align: 'center', width: 60, label: 'ID'},
          {type: 'normal', prop: 'label', align: 'center', minWidth: 200, label: '商品名称'},
          {type: 'normal', prop: 'key', align: 'center', width: 150, label: '键值'},
          {
            type: 'operate',
            align: 'center',
            prop: 'operate',
            width: 80,
            label: '操作',
            values: [
              {ui: 'button', icon: 'el-icon-delete', name: '删除', type: 'danger'},
            ]
          }
        ],
        selectData: [],
        show: false,
        tableRefresh: 'tableRefresh',
        
        //main
        formMainValue:{},
        formMainList: [
          {
            label: '', //label
            ele: 'slot', //package 名称
            slot: 'MAIN',
          }
        ],
        
        //远程搜索
        testResult: ["Alabama", "Alaska", "Arizona",
          "Arkansas", "California", "Colorado",
          "Connecticut", "Delaware", "Florida",
          "Georgia", "Hawaii", "Idaho", "Illinois",
          "Indiana", "Iowa", "Kansas", "Kentucky",
          "Louisiana", "Maine", "Maryland",
          "Massachusetts", "Michigan", "Minnesota",
          "Mississippi", "Missouri", "Montana",
          "Nebraska", "Nevada", "New Hampshire",
          "New Jersey", "New Mexico", "New York",
          "North Carolina", "North Dakota", "Ohio",
          "Oklahoma", "Oregon", "Pennsylvania",
          "Rhode Island", "South Carolina",
          "South Dakota", "Tennessee", "Texas",
          "Utah", "Vermont", "Virginia",
          "Washington", "West Virginia", "Wisconsin",
          "Wyoming"],
        testResultList: [],
        checkArray: [],
        
        
        //form
        xdSearchValue: [],
        XdBaseFieldValue: {},
        
        formListTest: [],
        token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9zYW5kYm94LWMuanVmdWJhby5jbiIsImlhdCI6MTY0MDE0NDI0MywiZXhwIjoxNjQwMjMwNjQzLCJhY2NvdW50X2lkIjo4LCJtZXJjaGFudF9pZCI6IjBfb05ua2M2SHVtd1JqV0Nja3c3WFBxdmNpbWJyWSIsInBsYXRmb3JtX2NvZGUiOiJ3eCIsImlwIjoiMTAuMC4yLjQiLCJjaGVja3N1bSI6ImFhYmNkNzJhNTRlYmE0MjI3MGMyODYzNzI1MTk5ODEyIn0.e7AgEQKtj_Ju7-_FQbTEdqZTpKs1DtX2RVe8ZH-MKoE',
        getCity: 'http://sandbox-c.jufubao.cn/api/pb/city/getsub',
        
      }
    },
    
    created(){
      
      this.testResultList = this.testResult.map(item => {
        return {value: `value:${item}`, label: `label:${item}`};
      });
      this.formListTest = this.getFormArray(this.getAllIds())
      
      
    },
    
    methods:{
      
      handleTableClick({index}){
        this.selectData.splice(index,1);
        console.log(this.selectData, index)
        //this.tableRefresh = Date.now();
      },
      handleShow(show){
        this.show = show
      },
      deepCloneFn(obj) {
        let objClone = Array.isArray(obj) ? [] : {};
        if (obj && typeof obj === "object") {
          for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
              if (obj[key] && typeof obj[key] === "object") {
                objClone[key] = this.deepCloneFn(obj[key]);
              } else {
                objClone[key] = obj[key];
              }
            }
          }
        }
        return objClone;
      },
      //下载============
      getSetting(id, key){
        let data = setting.filter(item => {
          return id === item.id
        });
        return this.deepCloneFn(data).map(item => {
          if (item.value.valueKey) {
            if (this.$xdHelper.checkVarType(item.value.valueKey) === 'string') {
              item.value.valueKey = item.value.valueKey.replace(/@key@/g, key);
            }
            if (this.$xdHelper.checkVarType(item.value.valueKey) === 'array') {
              item.value.valueKey = JSON.parse(JSON.stringify(item.value.valueKey).replace(/@key@/g, key));
            }
          }
          item.model = null;
          return item;
        })[0];
      },
      
      getAllIds(){
        return setting.map(item=>{
          return item.id;
        })
      },
      
      getFormArray(ids){
        return ids.map(id => {
          let key = 'from_' + this.$xdHelper.randomChar(10);
          return this.getSetting(id, key);
        });
      },
      
      getFormSetting(){
        return this.selectData.map(item=>{
          return item.value;
        })
      },
  
      getBeautify(content){
        return beautify['js_beautify'](content, Object.assign({
          "indent_with_tabs": false,
          "indent_size": 2,
          "jslint_happy": true,
          "end_with_newline": true,
          "space_after_anon_function": true,
          "brace_style": "preserve-inline",
        }))
      },
      
      handleClick(){
        if(this.selectData.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择生产动态插件库'
          });
          return
        }
        if(this.$route.path.indexOf('/dome/') !== -1) {
          this.$router.push(`/dome/dynamicForm?ids=${JSON.stringify(this.selectData.map(item => item.id))}`);
        }
        else{
          window.location.href = `/dynamicForm/dynamicForm?ids=${JSON.stringify(this.selectData.map(item => item.id))}`;
        }
       
      },
  
      handleAddClick(item){
        console.log(item)
        let key = 'from_' + this.$xdHelper.randomChar(10);
        this.selectData.push(this.getSetting(item.id, key));
      },
      //下载============
  
      /**
       * @description 获取配送区域
       * @param node 上级城市对象
       * @param resolve 回调地址
       */
      getDataRegionList(node, resolve) {
        let city = {
          0: [{"city_code": "1", "name": "\u5317\u4eac", "parent_id": "0"}, {
            "city_code": "31",
            "name": "\u65b0\u7586",
            "parent_id": "0"
          }, {"city_code": "4", "name": "\u91cd\u5e86", "parent_id": "0"}, {
            "city_code": "19",
            "name": "\u5e7f\u4e1c",
            "parent_id": "0"
          }, {"city_code": "3", "name": "\u5929\u6d25", "parent_id": "0"}, {
            "city_code": "15",
            "name": "\u6d59\u6c5f",
            "parent_id": "0"
          }, {"city_code": "52993", "name": "\u6e2f\u6fb3", "parent_id": "0"}, {
            "city_code": "20",
            "name": "\u5e7f\u897f",
            "parent_id": "0"
          }, {"city_code": "11", "name": "\u5185\u8499\u53e4", "parent_id": "0"}, {
            "city_code": "30",
            "name": "\u5b81\u590f",
            "parent_id": "0"
          }, {"city_code": "21", "name": "\u6c5f\u897f", "parent_id": "0"}, {
            "city_code": "32",
            "name": "\u53f0\u6e7e",
            "parent_id": "0"
          }, {"city_code": "14", "name": "\u5b89\u5fbd", "parent_id": "0"}, {
            "city_code": "24",
            "name": "\u8d35\u5dde",
            "parent_id": "0"
          }, {"city_code": "27", "name": "\u9655\u897f", "parent_id": "0"}, {
            "city_code": "8",
            "name": "\u8fbd\u5b81",
            "parent_id": "0"
          }, {"city_code": "6", "name": "\u5c71\u897f", "parent_id": "0"}, {
            "city_code": "29",
            "name": "\u9752\u6d77",
            "parent_id": "0"
          }, {"city_code": "22", "name": "\u56db\u5ddd", "parent_id": "0"}, {
            "city_code": "12",
            "name": "\u6c5f\u82cf",
            "parent_id": "0"
          }, {"city_code": "5", "name": "\u6cb3\u5317", "parent_id": "0"}, {
            "city_code": "26",
            "name": "\u897f\u85cf",
            "parent_id": "0"
          }, {"city_code": "84", "name": "\u9493\u9c7c\u5c9b", "parent_id": "0"}, {
            "city_code": "16",
            "name": "\u798f\u5efa",
            "parent_id": "0"
          }, {"city_code": "9", "name": "\u5409\u6797", "parent_id": "0"}, {
            "city_code": "2",
            "name": "\u4e0a\u6d77",
            "parent_id": "0"
          }, {"city_code": "17", "name": "\u6e56\u5317", "parent_id": "0"}, {
            "city_code": "23",
            "name": "\u6d77\u5357",
            "parent_id": "0"
          }, {"city_code": "25", "name": "\u4e91\u5357", "parent_id": "0"}, {
            "city_code": "28",
            "name": "\u7518\u8083",
            "parent_id": "0"
          }, {"city_code": "18", "name": "\u6e56\u5357", "parent_id": "0"}, {
            "city_code": "13",
            "name": "\u5c71\u4e1c",
            "parent_id": "0"
          }, {"city_code": "7", "name": "\u6cb3\u5357", "parent_id": "0"}, {
            "city_code": "10",
            "name": "\u9ed1\u9f99\u6c5f",
            "parent_id": "0"
          }],
          1: [{"city_code": "jfb1", "name": "\u5317\u4eac", "parent_id": "1"}, {
            "city_code": "bj-test1",
            "name": "\u5317\u4eac-\u6d4b\u8bd5",
            "parent_id": "1"
          }],
          jfb1: [{"city_code": "2812", "name": "\u987a\u4e49\u533a", "parent_id": "jfb1"}, {
            "city_code": "2807",
            "name": "\u95e8\u5934\u6c9f",
            "parent_id": "jfb1"
          }, {"city_code": "2803", "name": "\u5d07\u6587\u533a", "parent_id": "jfb1"}, {
            "city_code": "2810",
            "name": "\u5927\u5174\u533a",
            "parent_id": "jfb1"
          }, {"city_code": "2814", "name": "\u6000\u67d4\u533a", "parent_id": "jfb1"}, {
            "city_code": "2801",
            "name": "\u897f\u57ce\u533a",
            "parent_id": "jfb1"
          }, {"city_code": "2804", "name": "\u5ba3\u6b66\u533a", "parent_id": "jfb1"}, {
            "city_code": "2953",
            "name": "\u5e73\u8c37\u533a",
            "parent_id": "jfb1"
          }, {"city_code": "2816", "name": "\u5bc6\u4e91\u533a", "parent_id": "jfb1"}, {
            "city_code": "3065",
            "name": "\u5ef6\u5e86\u533a",
            "parent_id": "jfb1"
          }, {"city_code": "2802", "name": "\u4e1c\u57ce\u533a", "parent_id": "jfb1"}, {
            "city_code": "2901",
            "name": "\u660c\u5e73\u533a",
            "parent_id": "jfb1"
          }, {"city_code": "2805", "name": "\u4e30\u53f0\u533a", "parent_id": "jfb1"}, {
            "city_code": "72",
            "name": "\u671d\u9633\u533a",
            "parent_id": "jfb1"
          }, {"city_code": "2806", "name": "\u77f3\u666f\u5c71\u533a", "parent_id": "jfb1"}, {
            "city_code": "2808",
            "name": "\u623f\u5c71\u533a",
            "parent_id": "jfb1"
          }, {"city_code": "2800", "name": "\u6d77\u6dc0\u533a", "parent_id": "jfb1"}, {
            "city_code": "2809",
            "name": "\u901a\u5dde\u533a",
            "parent_id": "jfb1"
          }],
          2812: [{"city_code": "51130", "name": "\u5149\u660e\u8857\u9053", "parent_id": "2812"}, {
            "city_code": "51125",
            "name": "\u5317\u77f3\u69fd\u9547",
            "parent_id": "2812"
          }, {"city_code": "51147", "name": "\u6768\u9547\u5730\u533a", "parent_id": "2812"}, {
            "city_code": "51126",
            "name": "\u5317\u52a1\u9547",
            "parent_id": "2812"
          }, {"city_code": "51141", "name": "\u4ec1\u548c\u5730\u533a", "parent_id": "2812"}, {
            "city_code": "51139",
            "name": "\u5357\u6cd5\u4fe1\u5730\u533a",
            "parent_id": "2812"
          }, {"city_code": "51134", "name": "\u674e\u9042\u9547", "parent_id": "2812"}, {
            "city_code": "51138",
            "name": "\u5357\u5f69\u9547",
            "parent_id": "2812"
          }, {"city_code": "51127", "name": "\u5317\u5c0f\u8425\u9547", "parent_id": "2812"}, {
            "city_code": "51136",
            "name": "\u9a6c\u5761\u5730\u533a",
            "parent_id": "2812"
          }, {"city_code": "51135", "name": "\u9f99\u6e7e\u5c6f\u9547", "parent_id": "2812"}, {
            "city_code": "51140",
            "name": "\u725b\u680f\u5c71\u5730\u533a",
            "parent_id": "2812"
          }, {"city_code": "51142", "name": "\u80dc\u5229\u8857\u9053", "parent_id": "2812"}, {
            "city_code": "51146",
            "name": "\u65fa\u6cc9\u8857\u9053",
            "parent_id": "2812"
          }, {
            "city_code": "51131",
            "name": "\u540e\u6c99\u5cea\u5730\u533a",
            "parent_id": "2812"
          }, {"city_code": "51133", "name": "\u674e\u6865\u9547", "parent_id": "2812"}, {
            "city_code": "51128",
            "name": "\u5927\u5b59\u5404\u5e84\u9547",
            "parent_id": "2812"
          }, {"city_code": "51149", "name": "\u8d75\u5168\u8425\u9547", "parent_id": "2812"}, {
            "city_code": "51137",
            "name": "\u6728\u6797\u9547",
            "parent_id": "2812"
          }, {"city_code": "51143", "name": "\u77f3\u56ed\u8857\u9053", "parent_id": "2812"}, {
            "city_code": "51132",
            "name": "\u7a7a\u6e2f\u8857\u9053",
            "parent_id": "2812"
          }, {"city_code": "51129", "name": "\u9ad8\u4e3d\u8425\u9547", "parent_id": "2812"}, {
            "city_code": "51144",
            "name": "\u53cc\u4e30\u8857\u9053",
            "parent_id": "2812"
          }, {"city_code": "51145", "name": "\u5929\u7afa\u5730\u533a", "parent_id": "2812"}, {
            "city_code": "51148",
            "name": "\u5f20\u9547",
            "parent_id": "2812"
          }, {"city_code": "qweq123", "name": "\u5e73\u65b9\u8857\u9053", "parent_id": "2812"}]
        };
    
        let params = {city_code: 0, page_size: 10000};
        if (node.level > 0) {
          params['city_code'] = node['value'];
        }
        if (city[params['city_code']]) {
          let res = city[params['city_code']];
          if (node['level'] === 0) {
            res.splice(0, 0, {
              name: '全国',
              city_code: '0',
              leaf: true
            })
          }
          let temp = this.$xdHelper.idToSelectData(res, 'name', 'city_code', false);
          console.log('getDataRegionList', temp);
          temp.filter(item => {
            if (!item['leaf']) {
              item['leaf'] = false;
              //街道下无子节点
              if (node.level === 3) {
                item['leaf'] = true;
              }
            }
            return item;
          });
          console.log('resolve', temp);
          resolve(temp)
        } else {
          resolve([]);
        }
      },
      
      
      //搜索============
      handleRemoteSearch({query}, resolve){
        setTimeout(() => {
          let list = this.testResultList.filter(item => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
          resolve(list)
        }, 500);
      },
      handleSearch({form, action}) {
        console.log('handleSearch', form, action)
      },
  
      handleDone({form, action}) {
        console.log('handleDone', form, action)
      },
      //搜索============

      

      /**启动上传图片*******=======================================*/
      /**
       * @description 上传到本地服务器成功返回值时刻触发，设置url字段
       */
      handleApiSuccessUrl(result, resolve) {
        resolve(result.data['ObjectURL'])
      },
      /**
       * @description 上传参数设置
       * @param file
       * @param resolve
       */
      handleGetParamsAndHeader(file, resolve) {
        resolve({
          params: {
            token: genUpToken({
              accoutKey: 'bP3Ca5dtSJBNaWwMkihfhuE30CbAZnYrNzQm6eMN',
              serviceKey: 'pPNgWwRL3_Jlj7cPtpYbkhXn01EOZTtUhOs3NqZM',
              webSiteName: 'e56buystatic',
              staticUrl: 'http://static.e56buy.com',
            }),
            key: 'Xd' + this.$xdHelper.randomChar(30)
          }
        });
      },

      handleSuccess(res) {
        console.log(res)
      }
      /**启动上传图片*******=======================================*/
    }
  }

</script>

<style lang="scss" scoped>
  .app-container {
    padding: 20px;
    
    & ::v-deep .el-form-item__label {
      display: none;
    }
  
    & ::v-deep .el-form-item {
      margin-bottom: 0;
    }
    
    .xd-list {
      &__item {
        
        &-title {
          font-size: 14px;
          font-weight: bold;
          color: #333;
        }
        &-content {
          display: flex;
          width: 100%;
          justify-content: flex-start;
          align-items: center;
          min-height: 50px;
          box-shadow: 0 0 7px rgba(0, 0, 0, .2);
          margin: 20px 0;
          padding: 10px;
          
          & > div:first-child {
            flex:1;
          }
  
          & > div:last-child {
            flex-shrink: 0;
            width: 90px;
            text-align: right;
          }
        }
        
        
      }
    }

    &__item {
      margin-bottom: 20px;

      &-h1 {
        height: 50px;
        line-height: 50px;
        padding: 0 20px;
        font-weight: bold;
        background: #efefef;
        font-size: 16px;
        text-align: left;
        margin-bottom: 30px;
      }

      &-body {
        padding: 0 20px;

        &-value {
          padding-bottom: 10px;
        }
      }
    }

  }
  
  .xd-dialog {
    position: fixed;
    bottom: 10px;
    right: 200px;
    width: 700px;
    padding: 50px 10px 10px;
    box-shadow: 0 0 7px rgba(0, 0, 0, .2);
    border-radius: 6px;
    background: #fff;
    z-index: 999;
    
    &-btn {
      position: absolute;
      left: 10px;
      top: 10px;
      z-index: 9999;
    }
    
    &-title {
      position: absolute;
      top: 15px;
      left: 0;
      right: 15px;
      text-align: right;
      cursor: pointer;
    }
    
    &-content {
      overflow-y: auto;
    }
  }
</style>
