import routerUserMenu from '@/mixins/router-user-menu'
import breadcrumbComponent from '@/components/breadcrumb.vue'
import multipleSelectTree from '@/components/multiple-select-tree.vue'
import {toTree} from '@/utils/util'
import simpleSelectTree from '@/components/simple-select-tree.vue'
// import {echartsThemes} from '../../echarts-color-themes'
import {pieOptionData, lineAndBarOptionData , landscapeBarOption} from '../../../Report/ReportManagement/echarts-demo'
// 引入 vue-kikindeditor 需要的文件
import 'kindeditor/kindeditor-all-min.js'
import 'kindeditor/themes/default/default.css'
/**
 * KPI创建
 *  version = "1.0.0";
 *  author = "liucui";
 *  email = "liu.cui@data-u.com";
 * */
export default {
  name: 'chartAdd',
  components: {
    breadcrumbComponent, multipleSelectTree, simpleSelectTree
  },
  mixins: [routerUserMenu],
  data () {
    return {
      // 关联字段互斥ID
      mutexTableId: '',
      // 预览
      visible: false,
      previewData: '',
      fileList: [],
      // 数据对象 按表分组的字段
      colGroup: {},
      // 规则字段
      colOptions: [],
      // 主题树
      tree: [],
      // KPI类型
      typeOptions: [],
      // 分类
      chartClassOptions: [],
      // 数据库
      databaseOptions: [],
      // 表设置数据表
      tableOptions: [],
      // 定义字段
      columnOptions: [],
      // 配置类型
      configTypeOptions: [{id: "kpi", value: "KPI配置"}, {id: "DB", value: "数据库配置"}],
      // 富文本组件数组
      items: ['undo', 'redo', '|', 'preview', 'cut', 'copy', 'paste',
        'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
        'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
        'superscript', 'clearhtml', 'quickformat', 'selectall', 'formatblock', 'fontname', 'fontsize',
        '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
        'media', 'table', 'hr', 'emoticons', 'pagebreak', 'link', 'unlink'
      ],
      // 上传URL
      uploadJson: this.$api.chart.fileUpload,
      // 组件id（修改和查看）
      id: false,
      // 新建对象
      formInfo: {
        // 唯一标识
        id: '',
        // 图表名称
        chartName: '',
        // 图表json
        chartJson: '',
        // 图表分类
        chartClassCode: '',
        // 图表类型
        chartType: '',
        chartTypeName: '',
        // 数据库id
        databaseId: '',
        configType: '',//配置类型
        mapColor: '',//地图颜色
        axis: {x: '', y:['']},//XY轴
        interfaceId: '',//接口ID
        interfaceType:'',//接口分类
        paramNode:'',//出参节点
        mapStyle:[],//地图样式
        // dml
        dml: '',
        // 文件路径，图表类型为：图片、视频
        filePath: '',
        // 富文本文档，图表类型为：富文本
        richText: '',
        // 数据表id
        tableId: '',
        columnId: []
      },
      // 页面打开类型，false可编辑 true不可编辑
      readStatus: false,
      // 0新建 2修改
      dialogState: 0
    }
  },
  computed: {
    // 组件设置是否只读
    readonly: {
      // getter
      get: function () {
        return this.readStatus
      },
      // setter
      set: function (newValue) {}
    },
    /* 转换数据格式 */
    treeList: {
      get: function () {
        let tree = this.chartClassOptions
        // 线性数组转成树后渲染
        let defaultProps = {
          id: 'classCode',
          parent_id: 'pcode',
          label: 'className'
        }
        let newTree = toTree(tree, '0', defaultProps)
        return newTree
      }
    }
  },
  mounted () {
    // 获取图表类型
    this.getChartTypeOptions()
    // 图表分类
    this.getChartClassOptions()
    // 数据库
    this.getDatabaseOptions()
    // 加载table
    this.getTableOptions()
    // 加载表
    this.getColumnOptions()
    // 初始化
    this.init()
  },
  methods: {
    init () {
      // 获取url参数
      let params = this.$route.params
      if (params.hasOwnProperty('readonly')) {
        this.readStatus = true
      }
      if (params.hasOwnProperty('id')) {
        // 如果有id，则加载组件对象
        this.id = params.id
        // 如果有id，则获取id对应的部门信息赋值给formInfo
        this.getDetail()
        this.dialogState = 2
      }
      // 根据页面参数设置当前页面类型
    },
    afterUpload (url) {
      console.log(url);
    },
    // 获取组件对象
    getDetail () {
      let params = { id: this.id }
      let _this = this
      this.$api.chart.getChartById(params)
        .then(res => {
          if (res.code == 1) {
            if (res.data) {
              _this.formInfo = res.data
              let path  = _this.formInfo.filePath
              if (path && path.length > 0 ) {
                this.fileList = []
                let name = path.substring(path.lastIndexOf("/") + 1,path.length)
                this.fileList.push({name: name, url: path})
              }
            }
          }
        })
    },
    /* 上传前验证 */
    beforeAvatarUpload (file) {
      let chartType = this.formInfo.chartType
      let acceptFileTypes = chartType == 5 ? /(\.|\/)(png|jpg|jpeg|gif|svg|bmp|wmf|ico)$/i : /(\.|\/)(mp4)$/i
      const isAccept = acceptFileTypes.test(file.name)
      let isLt2M = chartType == 5 ? file.size / 1024 / 1024 < 2 : file.size / 1024 / 1024 < 500
      if (!isAccept) {
        let text = chartType == 5 ? "图片" : "MP4"
        this.$message.error('上传文件只能是' + text + '格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 500MB!')
        return false
      }
      return true
    },
    /**
     * 删除文件时
     * @param {*} e
     */
    fileRemove (file) {
      this.formInfo.filePath = ''
    },
    /** 文件上传 */
    uploadFile (e) {
      let file = e.raw
      let isCheck = this.beforeAvatarUpload(file)
      if (!isCheck) {
        return
      }
      // 封装form信息
      let param = new FormData() // 创建form对象
      param.append('file', file, file.name) // 通过append向form对象添加数据
      this.$api.chart.uploadFile(param)
        .then(res => {
          if (res.code == 1) {
            console.log(res.data)
            let path = res.data
            let name = path.substring(path.lastIndexOf("/") + 1,path.length)
            this.fileList = []
            this.fileList.push({name: name, url: path})
            this.formInfo.filePath = res.data
            // this.$emit('uploadSuccess',{param: result, result: res.data})
          }
        })
    },
    /* 获取图表类型列表 */
    getChartTypeOptions () {
      this.$api.chart.chartType().then(
        res => {
          if (res.code == 1) {
            this.typeOptions = res.data
          }
        })
    },
    /* 获取图表分类 */
    getChartClassOptions () {
      this.$api.chartType.getChartClassTree().then(
        res => {
          if (res.code == 1) {
            this.chartClassOptions = res.data
          }
        })
    },
    /* 获取数据库列表 */
    getDatabaseOptions () {
      this.$api.chart.listDatabase().then(
        res => {
          if (res.code == 1) {
            this.databaseOptions = res.data
          }
        })
    },
    /* 获取表信息 */
    getTableOptions (obj) {
      let params = { databaseId: obj }
      this.$api.chart.listTableByDatabaseId(params).then(
        res => {
          if (res.code == 1) {
            this.tableOptions = res.data
          }
        }
      )
    },
    /* 获取字段信息 */
    getColumnOptions (obj) {
      let params = {tableId: obj}
      this.$api.chart.listColumnByTableId(params).then(
        res => {
          if (res.code == 1) {
            this.columnOptions = res.data
          }
        }
      )
    },
    /* 获取表信息 */
    getDMLStr (obj) {
      let params = { tableId: obj.tableId, columnIds: obj.columnId }
      this.$api.chart.getDML(params).then(
        res => {
          if (res.code == 1) {
            this.formInfo.dml = res.data
          }
        }
      )
    },
    /* 选择类型 */
    typeChange (obj) {
      this.formInfo.chartType = obj.chartType
      let typeOptions = this.typeOptions
      for (let i = 0, len = typeOptions.length; i < len; i++) {
        if (typeOptions[i].id === obj.chartType) {
          this.formInfo.chartTypeName = typeOptions[i].value
          break
        }
      }
    },
    /* 定义/计算类型->选择数据库 */
    databaseChange (obj) {
      this.getTableOptions(obj.databaseId)
    },
    /* 定义类型选择表 */
    tableChange (obj) {
      this.getColumnOptions(obj.tableId)
    },
    /* 根据列获取DML */
    columnChange (obj) {
      this.getDMLStr(obj)
    },
    /* 提交新增节点 */
    add () {
      let _this = this
      // 判断组件设置是否通过验证
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          // 提交后台并在成功后回到上一页
          let params = _this.formInfo
          if (params.chartType == 2) {
            params.chartJson = JSON.stringify(lineAndBarOptionData)
          } else if (params.chartType == 3) {
            params.chartJson = JSON.stringify(pieOptionData)
          } else if (params.chartType == 8) {
            params.chartJson = JSON.stringify(landscapeBarOption)
          }
          _this.$api.chart.addChartInfo(params)
            .then(res => {
              if (res.code == 1) {
                _this.$message.success(res.msg)
                _this.goBack()
              }
            })
        } else {
          return false
        }
      })
    },
    /* 更新操作 */
    update () {
      let _this = this
      // 判断组件设置是否通过验证
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          // 提交后台并在成功后回到上一页
          let params = _this.formInfo
          if (params.columnId) {
            params.columnId = params.columnId.join(",")
          }
          _this.$api.chart.updateChartInfo(params)
            .then(res => {
              if (res.code == 1) {
                _this.$message.success(res.msg)
                _this.goBack()
              }
            })
        } else {
          return false
        }
      })
    },
    /* 预览功能 */
    preview () {
      this.previewData = ''
      let rules = this.formInfo.computedTypeInfo.ruleOptions
      for (let i = 0; i < rules.length; i++) {
        if (rules[i].isConstant === null || rules[i].isConstant === 'false') {
          let columnName = ''
          for (let j = 0; j < this.colOptions.length; j++) {
            if (rules[i].columnId == this.colOptions[j].id) {
              columnName = this.colOptions[j].columnName
              break
            }
          }
          this.previewData += rules[i].leftSign + columnName + rules[i].rightSign
        } else {
          this.previewData += rules[i].leftSign + rules[i].constant + rules[i].rightSign
        }
      }
      this.$alert(this.previewData, '预览规则')
    },
    /** 富文本编辑器 */
    onContentChange (val) {
      this.editorText = val
      this.formInfo.richText = val
    },
    /* 返回 */
    goBack () {
      this.$router.go(-1) // 返回上一层
    },
    delYaxis (index) {
      this.formInfo.axis.y.splice(index, 1)
    },
    addYaxis () {
      this.formInfo.axis.y.push("")
    }
  }
}
