
<template>
  <div class="page">
    <div>
      <a-select
        style="width: 150px"
        v-model="data_configureKey"
        @change="handleChange">
        <a-select-option
          v-for="(item,index) in templateData"
          :key="index"
          :value="item.id">
          {{ item.title }}
        </a-select-option>
      </a-select>
      <div class="tree-content">
        <a-tree
          show-line
          show-icon
          :tree-data="treeData"
          @select="onSelect"
          autoExpandParent
          :selectedKeys.sync="selectedKeys"
          :expandedKeys.sync="expandedKeys">
           <template #title="{ key: treeKey, title }">
            <a-dropdown :trigger="['contextmenu']">
              <span>{{ title }}</span>
              <template #overlay>
                <a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey)">
                  <a-menu-item key="1" v-if="treeKey.split('-').length<3">新增子节点</a-menu-item>
                  <a-menu-item key="2">删除</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </a-tree>
      </div>
    </div>
    <div class="right">
      <a-button-group>
        <a-button @click="handleOk">
          保存
        </a-button>
        <a-button>
          另存为
        </a-button>
        <a-button @click="addTemplate">
          新建模板
        </a-button>
      </a-button-group>
      <a-button style="margin-left:20px" @click="visible=true">
          查看json
        </a-button>
      <div class="form-content">
        <a-form-model layout="inline" ref="form_configure" :model="model" :rules="validatorRules" v-show="formType=='configure'">
          <div v-show="formType=='configure'">
            <a-form-model-item label="显示名称:" prop="configureTitle">
              <a-input
                style="width:170px"
                v-model="model.configureTitle"
              > </a-input>
            </a-form-model-item>
            <a-form-model-item
              label=""
              style="width: 244px"> </a-form-model-item>
            <a-form-model-item label="曲线类型:" prop="yType">
              <a-radio-group v-decorator="['radio-group']" style="width: 174px" v-model="model.yType">
                <a-radio value="time"> 时间 </a-radio>
                <a-radio value="deep"> 深度 </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </div>
        </a-form-model>
         <a-form-model layout="inline" ref="form_track" :model="model" :rules="validatorRules" v-show="formType=='track'">
          <div v-show="formType=='track'">
            <a-form-model-item label="显示名称:" prop="trackTitle">
              <a-input style="width:170px" v-model="model.trackTitle"> </a-input>
            </a-form-model-item>
            <a-form-model-item
              label=""
              style="width: 244px"> </a-form-model-item>
            <a-form-model-item label="宽度（像素）:" prop="width">
              <a-input-number style="width: 174px" v-model="model.width"></a-input-number>
            </a-form-model-item>
            <a-form-model-item
              label=""
              style="width: 244px"> </a-form-model-item>
            <a-form-model-item label="宽度是否固定:" prop="fix">
              <a-radio-group v-decorator="['radio-group']" v-model="model.fix">
                <a-radio value="1"> 是 </a-radio>
                <a-radio value="0"> 否 </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </div>
        </a-form-model>
        <a-form-model layout="inline" ref="form_line" :model="model" :rules="validatorRules" v-show="formType=='line'">
          <div v-show="formType=='line'">
            <a-form-model-item label="显示名称:" prop="lineTitle">
              <a-input style="width: 174px" v-model="model.lineTitle"> </a-input>
            </a-form-model-item>
            <a-form-model-item label="数据来源:" prop="dataSource">
              <j-dict-select-tag
                placeholder="请选择数据来源"
                dictCode="data_source"
                v-model="model.dataSource"
                style="width: 174px"
              />
            </a-form-model-item>
            <a-form-model-item label="曲线颜色:" prop="color">
              <colorPicker v-model="model.color" style="width: 174px" />
            </a-form-model-item>
            <a-form-model-item
              label="数据单位"
              prop="unit"> <a-input style="width: 174px" v-model="model.unit"> </a-input></a-form-model-item>
            <a-form-model-item label="起始最小值:" prop="minNum">
              <a-input-number style="width: 174px" v-model="model.minNum"></a-input-number>
            </a-form-model-item>
            <a-form-model-item label="起始最大值:" prop="maxNum">
              <a-input-number style="width: 174px" v-model="model.maxNum"></a-input-number>
            </a-form-model-item>
            <a-form-model-item label="是否自动扩展:" prop="spread">
              <a-radio-group v-decorator="['radio-group']" v-model="model.spread">
                <a-radio value="1"> 是 </a-radio>
                <a-radio value="0"> 否 </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item
              label=""
              style="width: 244px"> </a-form-model-item>
            <a-form-model-item label="扩展(最小):">
              <a-radio-group v-decorator="['radio-group']" v-model="model.minSpread">
                <a-radio value="a"> 按10取整 </a-radio>
                <a-radio value="b"> 自定义 </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="扩展(最大):">
              <a-radio-group v-decorator="['radio-group']" v-model="model.maxSpread">
                <a-radio value="a"> 按10取整 </a-radio>
                <a-radio value="b"> 自定义 </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="曲线类型" prop="lineStyle">
              <a-radio-group v-decorator="['radio-button']" v-model="model.lineStyle">
                <a-radio-button value="solid"> 折线 </a-radio-button>
                <a-radio-button value="smooth"> 平滑曲线 </a-radio-button>
                <a-radio-button value="step"> 阶梯 </a-radio-button>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item
              label=""
              style="width: 244px"> </a-form-model-item>
            <a-form-model-item label="背景:" prop="background">
              <a-radio-group v-decorator="['radio-group']" v-model="model.background">
                <a-radio value="value"> 平均分割 </a-radio>
                <a-radio value="log"> 指数 </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </div>
        </a-form-model>
      </div>
    </div>
    <a-modal
      v-model="visible" title="配置数据">
      <json-viewer
        :value="treeData"
        :expand-depth=5
        copyable
        boxed
      ></json-viewer>
      <template slot="footer">
        <a-button @click="visible=false">关闭</a-button>
      </template>
    </a-modal>
    <TemplateModel ref="templateModalForm" @ok="templateModalFormOk"/>
    <TrackModal ref="trackModalForm" @ok="trackModalFormOk"/>
    <LineModal ref="lineModalForm" @ok="trackModalFormOk"/>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import TemplateModel from '@/views/form/modules/templateModel'
import TrackModal from '@/views/form/modules/trackModel'
import LineModal from '@/views/form/modules/lineModel'
import {randomNumber} from '@/utils/util'
import { getTemplateList,
         getChartTreeList,
         duplicateCheckDataSource,
         deleteTrack,
         deleteLine,
         editTemplate,
         editTrack,
         editLine
          } from '@/api/api'
export default {
  name: 'ChartOptions',
  components:{
    TemplateModel,
    TrackModal,
    LineModal
  },
  props: {
     // 需要调整的曲线
    selectedKey: {
      type: [String, String],
      default: ''
    },
    // 下拉框被选中的模板
    configureKey: {
      type: [String, String],
      default: ''
    }
  },
  data () {
    return {
      templateData:[],
      treeData: undefined,
      visible:false,
      type:'edit',//当前操作类型:edit或者add
      form: this.$form.createForm(this, { name: 'options' }),
      data_selectedKey:this.selectedKey,
      data_configureKey:this.configureKey,
      expandedKeys: ['0'],
      selectedKeys: ['0'],
      formType: 'configure', // 当前表单范围
      model: {
        key: undefined,
        configureTitle: undefined,
        yType: undefined,
        trackTitle: undefined,
        width: undefined,
        fix: undefined,
        lineTitle: undefined,
        dataSource: undefined,
        color: '#000',
        minNum: undefined,
        maxNum: undefined,
        unit: undefined,
        spread: undefined,
        minSpread:undefined,
        maxSpread:undefined,
        lineStyle: undefined,
        background: undefined
      },
      validatorRules: {
          configureTitle: [{ required: true, message: '请输入名称!' }],
          trackTitle: [{ required: true, message: '不能为空!' }],
          width: [{ required: true, message: '不能为空!' }],
          fix: [{ required: true, message: '不能为空!' }],
          lineTitle: [{ required: true, message: '不能为空!' }],
          dataSource: [{ required: true, message: '不能为空!' },{validator: this.validateDataSource}],
          color: [{ required: true, message: '不能为空!' }],
          unit: [{ required: true, message: '不能为空!' }],
          minNum: [{ required: true, message: '不能为空!' }],
          maxNum: [{ required: true, message: '不能为空!' }],
          spread: [{ required: true, message: '不能为空!' }],
          lineStyle: [{ required: true, message: '不能为空!' }],
          background: [{ required: true, message: '不能为空!' }]
      }
    }
  },
   computed: {
    ...mapState({
    lineConfigSelected: state => state.lineConfig.lineConfigSelected
    }),
     ...mapState({
    chartData: state => state.lineConfig.chartData
    })
   },
  async created () {
    this.clearModel()
    await this.getTemplate()
    await this.getTreeData(this.data_configureKey)
    this.onSelect([this.data_selectedKey], '')
    this.expandedKeys =[]
    this.expandedKeys.push(this.data_selectedKey)
    this.selectedKeys =[]
    this.selectedKeys.push(this.data_selectedKey)
  },
  mounted () {
  },
  methods: {
    /* 获取所有模板 */
    async getTemplate(){
      let _this=this
      await getTemplateList().then((res)=>{
        if(res.success){
          _this.templateData = [...res.result]
          if(_this.data_configureKey===''){
            _this.data_configureKey=res.result[0].id
          }
        }
      })

    },
    /* 获取树数据 */
   async getTreeData(id){
       const _this=this
       await getChartTreeList({id:id}).then((res)=>{
        if(res.success){
           _this.treeData=[...res.result]
          _this.$store.commit('SET_KEY', _this.data_configureKey)
        }
      })
    },
    /* 配置下拉框选择配置 */
    async handleChange (value) {
      this.data_configureKey=value
      await this.getTreeData(value)
      this.treeData.forEach(item => {
        if (item.key === value) {
          this.expandedKeys = [item.key]
          this.selectedKeys= [item.key]
          this.onSelect([item.key], '')
        }
      })
    },
    /* 新增模板 */
    addTemplate(){
      this.$refs.templateModalForm.add();
      this.$refs.templateModalForm.title = "新增模板";
      this.$refs.templateModalForm.disableSubmit = false;
    },
    async templateModalFormOk(id) {
       await this.getTemplate()
       await this.getTreeData(id)
       this.onSelect([id], '')
       this.data_configureKey=id
       this.expandedKeys =[]
       this.expandedKeys.push(id)
       this.selectedKeys =[]
       this.selectedKeys.push(id)
    },
    async trackModalFormOk(id){
       await this.getTreeData(this.data_configureKey)
       this.onSelect([id], '')
       this.expandedKeys =[]
       this.expandedKeys.push(id)
       this.selectedKeys =[]
       this.selectedKeys.push(id)
    },
     /* 树的右键 */
    onContextMenuClick(treeKey, menuKey) {
      // 新增子节点
      if(menuKey==='1'){
        const keyLength=treeKey.split('-')
        if (keyLength.length === 1) {
          this.$refs.trackModalForm.add(treeKey);
          this.$refs.trackModalForm.title = "新增曲线道";
          this.$refs.trackModalForm.disableSubmit = false;
        } else if (keyLength.length === 2) {
          this.$refs.lineModalForm.add(treeKey);
          this.$refs.lineModalForm.title = "新增曲线";
          this.$refs.lineModalForm.disableSubmit = false;
        }
      }
      if(menuKey==='2'){
       const _this = this
       this.$confirm({
        title: '是否确认删除?',
        onOk () {
            const keyLength=treeKey.split('-').length
            if (keyLength === 2) {
              deleteTrack({id:treeKey.split('-')[1]}).then((res)=>{
                 if (res.success) {
                    _this.$message.success(res.message);
                    _this.getTreeData(_this.data_configureKey)
                    _this.$store.commit('line_config_options', 'init'+'_'+randomNumber(8))
                  } else {
                    _this.$message.warning(res.message);
                  }
              })
            } else if (keyLength === 3) {
              deleteLine({id:treeKey.split('-')[2]}).then((res)=>{
                 if (res.success) {
                    _this.$message.success(res.message);
                    _this.getTreeData(_this.data_configureKey)
                    _this.$store.commit('line_config_options', 'init'+'_'+randomNumber(8))
                  } else {
                    _this.$message.warning(res.message);
                  }
              })
            }

        },
        onCancel () {}
       })
      }
    },
    clearModel () {
      this.model = {
        key: null,
        configureTitle: undefined,
        yType: undefined,
        trackTitle: undefined,
        width: undefined,
        fix: undefined,
        lineTitle: undefined,
        dataSource: undefined,
        unit:undefined,
        color: '#000',
        minNum: undefined,
        maxNum: undefined,
        spread: undefined,
        minSpread:undefined,
        maxSpread:undefined,
        lineStyle: undefined,
        background: undefined
      }
    },
    /* 给表单赋值 */
    setModel (key) {
      const currentDate = this.treeData[0]
      if (this.treeData.length > 0 && this.formType === 'configure') {
        this.model.configureTitle = currentDate.title
        this.model.yType = currentDate.yType
      }
      if (currentDate.children && this.formType === 'track') {
          this.clearModel()
          const index = currentDate.children.findIndex(n => n.key === key)
          const trackData = currentDate.children[index]
          this.model.trackTitle = trackData.title
          this.model.width = trackData.width
          this.model.fix = trackData.fix
          this.model.key = key
        }
      if (this.formType === 'line') {
        console.log(key)
        this.clearModel()
        let ids=key.split('-')
        const pKey = ids[1]
        const pIndex = currentDate.children.findIndex(n => n.id === pKey)
        const index = currentDate.children[pIndex].children.findIndex(n => n.key === key)
        const lineData = currentDate.children[pIndex].children[index]
        this.model.lineTitle = lineData.title
        this.model.dataSource = lineData.dataSource
        this.model.color = lineData.color
        this.model.unit = lineData.unit
        this.model.minNum = lineData.minNum
        this.model.maxNum = lineData.maxNum
        this.model.spread = lineData.spread
        this.model.minSpread=lineData.minSpread
        this.model.maxSpread=lineData.maxSpread
        this.model.lineStyle = lineData.lineStyle
        this.model.background = lineData.background
        this.model.key = key
      }
    },
    /* 树节点点击事件 */
    onSelect (selectedKeys, info) {
      if (selectedKeys.length > 0) {
        this.model.key = selectedKeys[0]
        this.getFormType(selectedKeys[0])
        if (this.$refs.form_configure) {
           this.$refs.form_configure.resetFields()
        }
        if (this.$refs.form_track) {
           this.$refs.form_track.resetFields()
        }
        if (this.$refs.form_line) {
           this.$refs.form_line.resetFields()
        }
        this.setModel(selectedKeys[0])
      }
    },
    /* 根据key判断显示表单类型 */
    getFormType (key) {
      const keyLength=key.split('-').length
      if (keyLength === 1) {
        this.formType = 'configure'
      } else if (keyLength === 2) {
        this.formType = 'track'
      } else if (keyLength === 3) {
        this.formType = 'line'
      }
    },
     validateDataSource(rule, value, callback){
        const currentDate = this.treeData[0]
        let ids=this.model.key.split('-')
        const pKey = ids[1]
        const pIndex = currentDate.children.findIndex(n => n.id === pKey)
        const index = currentDate.children[pIndex].children.findIndex(n => n.key ===this.model.key)
        const lineData = currentDate.children[pIndex].children[index]
        var params = {
          trackId: pKey,
          id:lineData.id,
          dataSource: value
        }
         console.log(params)
        duplicateCheckDataSource(params).then((res) => {
          if (res.success) {
          callback()
        } else {
          callback("此数据源已存在!")
        }
      })
      },
    /* 保存事件 */
    handleOk () {
      let obj
      let parms={}
      parms={...this.model}
      const _this=this
      if(this.formType==='configure'){
          this.$refs.form_configure.validate(valid => {
            if (valid) {
              parms.id=_this.model.key
              parms.title=_this.model.configureTitle.trim()
              editTemplate(parms).then((res)=>{
                if (res.success) {
                  _this.$message.success(res.message)
                  _this.getTreeData(_this.data_configureKey)
                  _this.expandedKeys =[]
                  _this.expandedKeys.push(_this.model.key)
                  _this.selectedKeys =[]
                  _this.selectedKeys.push(_this.model.key)
                  _this.$store.commit('line_config_options', 'update'+'_'+randomNumber(8))
                  } else {
                  _this.$message.warning(res.message)
                  }
              })
            }
          })
      }else if(this.formType==='track'){
        this.$refs.form_track.validate(valid => {
            if (valid) {
              parms.id=_this.model.key.split('-')[1]
              parms.title=_this.model.trackTitle.trim()
              editTrack(parms).then((res)=>{
                if (res.success) {
                  _this.$message.success(res.message)
                  _this.getTreeData(_this.data_configureKey)
                  _this.expandedKeys =[]
                  _this.expandedKeys.push(_this.model.key)
                  _this.selectedKeys =[]
                  _this.selectedKeys.push(_this.model.key)
                  _this.$store.commit('line_config_options', 'update'+'_'+randomNumber(8))
                  } else {
                  _this.$message.warning(res.message)
                  }
              })
            }
          })

      }else if(this.formType==='line'){
          this.$refs.form_line.validate(valid => {
            if (valid) {
               parms.id=_this.model.key.split('-')[2]
               parms.title=_this.model.lineTitle.trim()
               editLine(parms).then((res)=>{
                  if (res.success) {
                    _this.$message.success(res.message)
                    _this.getTreeData(_this.data_configureKey)
                    _this.expandedKeys =[]
                    _this.expandedKeys.push(_this.model.key)
                    _this.selectedKeys =[]
                    _this.selectedKeys.push(_this.model.key)
                    _this.$store.commit('line_config_options', 'update'+'_'+randomNumber(8))
                    } else {
                    _this.$message.warning(res.message)
                    }
                })
            }
          })

      }
    }
  }
}
</script>

<style scoped>
.m-colorPicker /deep/ .box.open{
  z-index: 1000;
}
.m-colorPicker /deep/ .colorBtn{
  width:175px;
  height: 20px;
}
.page {
  font-size: 5px;
  width: 100%;
  height: 600px;
  display: flex;
}
.tree-content {
  border: 1px solid black;
  margin-top: 5px;
  height: 500px;
  overflow: scroll;
  width:200px
}
.right {
  margin-left: 20px;
  width: 800px;
}
.form-content {
  border: 1px solid black;
  margin-top: 5px;
  height: 500px;
  padding: 10px;
}
</style>
