<template>
  <div>
    <manager-ui
      ref="form"
      :loading="loading"
      :query-model="qureyParam"
      :query-items="queryItems"
      :static-data="staticData"
      :column-items="columnItems"
      :table-data="tableData"
      :pagination="page"
      :showDownloadBtn="false"
      show-table-tools
      @create="openDialog('add')"
      @selection-change="handleSelectionChange"
      @searchClick="searchClick"
      @search="search"
      @resetForm="reset"
    >
      <template slot="layoutLabel" slot-scope="scope">
        <span>{{ scope.scope.row.layoutLabel|toCase(staticData.layoutLabelList,'value', 'label') }}</span>
      </template>
      <template slot="layoutType" slot-scope="scope">
        <span>{{ scope.scope.row.layoutType|toCase(staticData.layoutTypeList,'value', 'label') }}</span>
      </template>
      <template slot="layoutIcon" slot-scope="scope">
        <el-image
          style="width: 30px; height: 30px"
          :src="encodeFilePath(scope.scope.row.layoutIcon)"
          fit="fit" 
        />
      </template>
      <template #businessIds>
        <el-form-item label="归属系统:">
          <manager-tree-select 
            class="horizontalTreeSelect"
            ref="businessTree"
            v-model="qureyParam.businessIds" 
            :data="businessTree" 
            :defaultProps="{
              label: 'label',
              children: 'children',
              disabled: 'specTag'
            }"
            @clear="qureyParam.businessIds = []; $refs.businessTree.filterText = ''" 
          />
        </el-form-item>
      </template>
      <template slot="operaiton" slot-scope="scope">
        <el-context-menu :menus="menus" :scope="scope.scope" :default="3" @oper="clickRow" />
      </template>
      <template slot="tableTools">
        <el-button type="text" icon="el-icon-delete-solid" @click="handleDelete">删除</el-button>
      </template>
    </manager-ui>
    <Dialog
      ref="dialog"
      :command="command"
      :row="row"
      :statics="staticData"
      @success="search"
    />
    <TestDialog ref="testDialog" :row="row" />
  </div>
</template>
<script>
import table from '@ability/mixins/table'
import staticsData from '@ability/mixins/staticsData'
import { baseUrl } from '@ability/utils/request'
import { getObjectList, removeObject } from '../api'
import Dialog from './Dialog'
import TestDialog from './TestDialog'
export default {
  components: { Dialog, TestDialog },
  mixins: [table, staticsData],
  watch: {
    'qureyParam.businessIds'(value) {
      if (!value) return
      let val = this.getCascaderSelectIds(this.businessTree, value[0], 'dataId', 'children', 'label').slice(-1)[0]
      this.$refs.form.setQueryStrategies({key: 'businessIds', label: '归属系统', value: val})
    }
  },
  data() {
    return {
      filterBusinessTree: [],
      loading: false,
      baseUrl: baseUrl,
      qureyParam: {
        layoutName: '',
        layoutCode: '',
        layoutType: null,
        businessIds: []
      },
      queryItems: [
        {
          type: 'input',
          span: 12,
          key: 'layoutName',
          label: '编排对象名称'
        },
        {
          type: 'input',
          span: 12,
          key: 'layoutCode',
          label: '编排对象编码'
        },
        {
          type: 'select',
          span: 12,
          key: 'layoutType',
          placeholder: '请选择业务类型',
          label: '业务类型',
          option: 'layoutTypeList',
          optionLabel: 'label',
          optionValue: 'value',
          clearable: true
        },
        // {
        //   type: 'treeSelect',
        //   span: 12,
        //   key: 'businessIds',
        //   placeholder: '请选归属系统',
        //   label: '归属系统',
        //   dataTree: 'businessTree'
        // },
        {
          span: 12,
          type: 'slot',
          key: 'businessIds',
          slot: 'businessIds',
          label: '归属系统'
        }
      ],
      columnItems: [
        {
          type: 'selection',
          width: 50
        },
        {
          _key: 'layoutName',
          prop: 'layoutName',
          label: '编排对象名称',
          showOverflowTooltip: true
        },
        {
          _key: 'layoutCode',
          prop: 'layoutCode',
          label: '编排对象编码',
          showOverflowTooltip: true
        },
        {
          _key: 'businessName',
          prop: 'businessName',
          label: '归属系统',
          showOverflowTooltip: true
        },
        {
          _key: 'layoutLabel',
          prop: 'layoutLabel',
          label: '标签',
          showOverflowTooltip: true,
          render: true
        },
        {
          _key: 'layoutType',
          prop: 'layoutType',
          label: '业务类型',
          showOverflowTooltip: true,
          render: true
        },
        {
          _key: 'layoutIcon',
          prop: 'layoutIcon',
          label: '图标',
          showOverflowTooltip: true,
          render: true
        },
        {
          _key: 'interfaceAddress',
          prop: 'interfaceAddress',
          label: '后端地址',
          showOverflowTooltip: true
        },
        {
          _key: 'layoutDesc',
          prop: 'layoutDesc',
          label: '描述',
          showOverflowTooltip: true
        },
        {
          _key: 'createUser',
          prop: 'createUser',
          label: '创建人',
          showOverflowTooltip: true
        },
        {
          _key: 'createTime',
          prop: 'createTime',
          label: '创建时间',
          showOverflowTooltip: true
        },
        {
          _key: 'operaiton',
          prop: 'operaiton',
          width: '115px',
          label: '操作',
          showOverflowTooltip: true,
          render: true
        }
      ],
      tableData: [],
      command: '',
      row: null,
      menus: [
        {
          text: '查看',
          command: 'detail',
          icon: 'el-icon-s-order'
          // ruleCode: 'rightRuleManage_del'
        },
        {
          text: '修改',
          command: 'edit',
          icon: 'el-icon-edit'
          // ruleCode: 'rightRuleManage_update'
        },
        {
          text: '删除',
          command: 'delete',
          icon: 'el-icon-delete',
          iconColor: 'red'
          // ruleCode: 'rightRuleManage_del'
        },
        {
          text: '测试',
          command: 'test'
          // ruleCode: 'rightRuleManage_del'
        }
      ]
    }
  },
  computed: {
    staticData() {
      return {
        layoutTypeList: [
          { label: '费用', value: '1' },
          { label: '资料', value: '2' },
          { label: '清单', value: '3' }
        ],
        layoutLabelList: [
          {
            value: '1',
            label: '生活服务'
          },
          {
            value: '2',
            label: '金融科技'
          },
          {
            value: '3',
            label: '交通地理'
          },
          {
            value: '4',
            label: '充值缴费'
          },
          {
            value: '5',
            label: '数据智能'
          },
          {
            value: '6',
            label: '应用开发'
          }
        ],
        businessTree: this.businessTree
      }
    }
  },
  async created() {
    this.search()
    await this.getBusinessTree()
    let toggleTree = tree => {
      if (tree) {
        tree.forEach(el => {
          if (el.children && el.children.length) {
            el.specTag = true
            toggleTree(el.children)
          } else {
            el.specTag = !el.specTag
          }
        })
      }
    } 
    toggleTree(this.businessTree)
  },
  methods: {
    toggleTree(tree) {

    },
    hasNode(o, chiledName) {
      return o[chiledName] && o[chiledName].length > 0;
    },
    getCascaderSelectIds(tree, id, idname, chiledName, returnName) {
      var result = []
      if (tree) {
        tree.forEach((item) => {
          if (item[idname] == id) {
            result.push(item[returnName || idname]);
            return result;
          } else {
            var flag = this.hasNode(item, chiledName);
            if (flag) {
              var tmp = this.getCascaderSelectIds(item[chiledName], id, idname, chiledName, returnName);
              if (tmp.length > 0) {
                result.push(item[returnName || idname])
                tmp.forEach(function(sItem) {
                  result.push(sItem)
                })
                return result;
              } else {
                return [];
              }
            } else {
              return [];
            }
          }
        })
      }
      return result;
    },
    encodeFilePath(url) {
      if (!url || typeof url != 'string') return
      url = url.split('/')
      let filePath = url.pop()
      return this.baseUrl + '/analyze/' + url.join('/') + '/' + encodeURIComponent(filePath)
    },
    clickRow(command, scope) {
      if (command === 'edit') {
        this.openDialog('modify', scope.row)
      }
      if (command === 'delete') {
        this.handleDelete(scope.row)
      }
      if (command === 'detail') {
        this.openDialog('detail', scope.row)
      }
      if (command === 'test') {
        this.openDialog('test', scope.row)
      }
    },
    openDialog(command, row) {
      this.command = command
      if (command !== 'add' && row) {
        this.row = row
      }
      if (this.command === 'test') {
        this.row = row
        this.$refs.testDialog.dialogVisible = true
      } else this.$refs.dialog.dialogVisible = true
    },
    handleDelete(row) {
      let id = []
      if (row.layoutId) {
        id = [row.layoutId]
      } else {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请至少选择一项')
          return
        } else {
          id = this.multipleSelection.map((obj) => obj.layoutId)
        }
      }
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          removeObject({
            id
          })
            .then((resp) => {
              if (resp.data.returnCode == '0') {
                this.$message.success('删除成功')
                if (this.tableData.length == 1 || (!row && this.multipleSelection.length)) this.page.current = --this.page.current || 1
                this.search()
              }
            })
        })
    },
    searchClick() {
      this.page.current = 1
      this.search()
    },
    reset() {
      this.qureyParam.businessIds = []
      this.$refs.businessTree.filterText = ''
      this.page.current = 1
      this.search()
    },
    search() {
      this.loading = true
      const layouobjectInfoMap = JSON.parse(JSON.stringify(this.qureyParam))
      if (layouobjectInfoMap.businessIds && layouobjectInfoMap.businessIds.length === 0) {
        layouobjectInfoMap.businessIds = null
      }
      getObjectList(
        {
          layouobjectInfoMap,
          page: this.page
        }
      )
        .then((resp) => {
          if (resp.data.returnCode == '0') {
            this.tableData = resp.data.data.list
            const { current, size, total } = resp.data.data.page
            this.page.current = current
            this.page.size = size
            this.page.total = total
          }
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
    }
  }
}
</script>