<template>
  <div v-dee-loading="loading" class="xform-page">
    <div v-if="showDetail" class="header-bar">
      <span v-show="base&&base.showTitle" class="title">
        <img v-show="iconMap[typeName] && showTitleParams.length && showTitleParams[0].attr" class="partIcon" :src="iconMap.hasOwnProperty(typeName)?iconMap[typeName]:''" alt="">
        <span v-for="(attr,index) in showTitleParams" :key="index" :style="attr.style">
          {{ attr.title }}
        </span>
        <span v-show="versionControl && showTitleParams.length" class="checkoutInfo">{{ checkoutInfo }}</span>
      </span>
      <dee-tools
        v-if="isView===false&&base&&base.showTools&&tableObj&& tableObj.toolList&& tableObj.toolList.length"
        :tools="showTools"
        :perm-enable="true"
        :hide-tool-keys="hideToolKeys"
        :permissions="showPermissions"
        @handerToolFun="handlerToolFun"
      />
    </div>
    <dee-tab
      :type-name="typeName"
      :page-data="pageData"
      :prop-form="basicData"
      :tabs="showComponentsData"
      :is-work-item="true"
      :model-name="modelName"
      :permissions="showPermissions"
      :business-data="businessData || {}"
      :checkout-state="checkoutState"
      style="margin: 0 10px"
      @tableToolHandler="tableToolHandler"
      @tableRowBtnClick="tableRowBtnClick"
    />
  </div>
</template>

<script>
import { getDetailWithRecursion, getDocStatus } from '@/api/searchCom'
import _get from 'lodash.get'
export default {
  name: 'XForm',
  props: {
    base: {
      type: Object,
      default: () => null
    },
    pageData: {
      type: Object,
      default: () => {}
    },
    hideToolKeys: {
      type: Array,
      default: () => []
    },
    businessData: {
      type: Object,
      default: () => null
    },
    typeName: {
      type: [Number, String],
      default: () => {
      }
    },
    componentsData: {
      type: Array,
      default: () => []
    },
    tableObj: {
      type: Object,
      default: () => null
    },
    isShowEditBtn: {
      type: Boolean,
      default: () => false
    },
    isView: {
      type: Boolean,
      default: false
    },
    permissions: {
      type: [Array, Object],
      default: () => null
    },
    modelName: {
      type: String,
      default: () => ''
    },
    versionControl: {
      type: Boolean,
      default: true
    },
    notWorkCopy: {
      type: Boolean,
      default: false
    },
    defaultData: {
      type: Object,
      default: () => null
    },
    toolEvent: {
      type: Object,
      default: () => null
    },
    expandProps: {
      type: [Array],
      default: () => []
    },
    cmpOptions: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      iconMap: {
        default: '/icons/c-partg.png'
      },
      loading: false,
      propForm: {},
      basicData: null,
      checkoutState: {},
      userId: '',
      stateOption: [],
      showPermissions: []
    }
  },
  computed: {
    showDetail() {
      if (!this.permissions || !this.permissions.length) {
        return true
      }
      const perm = this.permissions.find(p => p.keyName.includes('detailPage'))
      if (!perm) {
        return true
      }
      return perm.hadPage
    },
    showTools() {
      if (!this.tableObj || !this.tableObj.toolList) {
        return []
      }
      return this.tableObj.toolList
    },
    showTitleParams() {
      if (!this.basicData) {
        return []
      }
      if (!this.tableObj || !this.tableObj.titleParams) {
        return []
      }
      return this.tableObj.titleParams.map(attr => {
        let title = _get(this.basicData, attr.attr) || ''
        if (attr.placeholder) {
          title = attr.placeholder.replace(/\$\*/, title)
        }
        if (attr.connector) {
          title += attr.connector
        }
        return {
          style: attr.style,
          title: title
        }
      })
    },
    checkoutInfo() {
      let checkoutInfo = ''
      if (this.checkoutState && this.checkoutState.checkout) {
        checkoutInfo = this.checkoutState.isCheckouter ? `已由你检出` : `已由${this.checkoutState.lockerName}检出`
      } else {
        checkoutInfo = this.basicData && this.basicData.checkOuted ? '已检出' : '未检出'
      }
      return checkoutInfo
    },
    showVersionControl() {
      if (!this.versionControl) {
        return false
      }
      return !this.notWorkCopy
    },
    toValidateKeys() {
      if (!this.permissions) {
        return null
      }
      return this.permissions.filter(r => r.hadPage).map(r => r.keyName)
    },
    statusUrl() {
      return `${this.modelName}/version/getWorkingCopy/{{id}}`
    },
    detailUrl() {
      return `${this.modelName}/find/recursion`
    },
    keyName() {
      if (!this.cmpOptions || this.cmpOptions.typeName || this.cmpOptions.value) {
        return ''
      }

      return `${this.cmpOptions.typeName}-${this.cmpOptions.value}`
    },
    showComponentsData() {
      if (!this.permissions || !this.permissions.length) {
        return this.componentsData
      }
      let componentsData = [...this.componentsData]
      if (this.componentsData) {
        const perms = this.permissions
        const keyName = this.keyName

        componentsData.forEach((tab, index) => {
          const key = keyName + ':' + (tab.key || ('tab' + index))
          const perm = perms.find(r => r.keyName === key)
          if (perm) { // tab 页签配置权限
            if (perm.hadPage) {
              tab.data = this.filterTab(tab.data, perms, keyName)
            } else { // 没权限
              tab.hidden = true
            }
          } else { // tab 页签配置没有权限
            tab.data = this.filterTab(tab.data, perms, keyName)
          }
        })
      }
      componentsData = componentsData.filter(tab => tab.hidden !== true)
      return componentsData
    }
  },
  watch: {
    defaultData: {
      immediate: true,
      handler: function(val) {
        if (val) {
          this.propForm = { ...val }
          this.getDetail(val.id)
        }
      }
    },
    permissions: {
      immediate: true,
      handler: function(val) {
        if (val) {
          this.showPermissions = [...val]
        }
      }
    }
  },
  // 生命周期 - 创建完成(访问当前this实例)
  created() {
    this.userId = parseInt(localStorage.getItem('userId'))
    this.getStateList()
  },
  // 生命周期 - 挂载完成(访问DOM元素)
  mounted() {

  },
  methods: {
    filterTab(list, perms, keyName) {
      return list.filter(cmp => {
        const key = keyName + ':' + cmp.value || cmp.permKey
        const perm = perms.find(r => r.keyName === key)
        if (perm) {
          return perm.hadPage
        }
        return true
      })
    },
    getState(key) {
      return this.$utils.getParamsFromLists(this.stateOption, 'value', key, 'label') || key
    },
    reload() {
      this.defaultData && this.getDetail(this.defaultData.id)
    },
    getDetail(id) {
      if (this.loading || !id) {
        return
      }
      if (this.notWorkCopy || !this.versionControl) { // 没有副本 或没有版本控制
        this.propForm.copyId = this.propForm.id
        this.checkoutState = { }
        this.getBasicData()
        return
      }
      this.loading = true
      getDocStatus(this.$utils.attachTemplateToData(this.statusUrl, { id })).then(res => {
        this.propForm.id = id
        if (res.items) {
          if (res.items.lockerId === this.userId) {
            this.isShowEditBtn = true
            this.propForm.copyId = res.items.id
          } else {
            this.propForm.copyId = this.propForm.id
          }
          this.checkoutState = {
            checkout: true,
            id: this.propForm.id,
            isCheckouter: res.items.lockerId === this.userId,
            lockerName: res.items.locker ? res.items.locker.userName : ''
          }
        } else {
          this.propForm.copyId = this.propForm.id
          this.checkoutState = { checkout: false }
        }
        this.getBasicData()
        sessionStorage.setItem('getLastId', this.propForm.copyId)
      }).catch(e => {
        this.loading = false
      })
    },
    async getStateList() {
      this.stateOption = await this.$utils.getDicListByCode('ObjStatus')
    },
    getBasicData() {
      this.loading = true
      getDetailWithRecursion({
        id: this.propForm.copyId,
        expandProps: this.expandProps,
        toValidateKeys: this.toValidateKeys,
        url: this.detailUrl
      }).then(res => {
        this.loading = false
        if (res.items && res.items.content) {
          this.basicData = this.$utils.getDynamicAttr(res.items.content[0])
          if (this.basicData.state) {
            this.basicData.state = this.getState(this.basicData.state)
          }
          if (this.toValidateKeys) {
            this.toValidateKeys.forEach(key => {
              const perm = this.permissions.find(p => p.keyName === key)
              if (perm) {
                perm.hadPage = false
              }
            })
            this.basicData.permissions && this.basicData.permissions.forEach(r => {
              const perm = this.permissions.find(p => p.keyName === r)
              const indx = this.permissions.findIndex(p => p.keyName === r)
              if (perm) {
                perm.hadPage = true
                this.$set(this.showPermissions, indx, perm)
              }
            })
          }
        }
      }).catch(() => {
        this.loading = false
      })
    },
    handlerToolFun(functionKey) {
      this.$emit('toolsEvent', { key: functionKey, el: this })
      if (this.toolEvent && this.toolEvent[functionKey]) {
        this.toolEvent[functionKey](this.propForm)
      }
    },
    tableToolHandler(e) {
      this.$emit('tableToolHandler', e)
    },
    tableRowBtnClick(e) {
      this.$emit('tableRowBtnClick', e)
    }
  }
}
</script>
<style lang="scss">
/* @import url(); 引入css类 */
.xform-page{
  overflow-y: hidden;
  box-sizing: border-box;
  height: 100%;
  width: 100%;
  padding: 5px;
  .header-bar {
    line-height: 24px;
    margin: 20px 0 10px;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .title {
      font-weight: bold;
      padding-left: 10px;
      font-size: 14px;
      .partIcon{
        display: inline-block;
        width: 16px;
        height: 16px;
        margin-right: 3px;
        vertical-align: middle;
      }
    }

    .checkoutInfo {
      font-size: 12px;
      font-weight: 600;
      color: #606266;
    }
  }
}
</style>