<template>
  <div class="app-container">
    <el-drawer
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      top="4%"
      size="43%"
      style="overflow: auto"
    >
      <el-form
        ref="form"
        v-loading="loading"
        :model="formItem"
        :label-width="'100px'"
      >
        <el-form-item
          v-if="superAdmin"
          :label="$t('ec.user.tenant')"
          prop="tenantId"
        >
          <ec-tenant-by-pro
            v-model="formItem.tenantId"
            :disabled="method ==='edit'"
          />
        </el-form-item>
        <el-form-item
          :label="$t('ec.table.name')"
          prop="name"
          :rules="[
            {required: true, message: $t('ec.table.name') + $t('ec.table.emptyError'), trigger:'blur'}
          ]"
        >
          <el-input
            v-model="formItem.name"
            type="text"
            :placeholder="$t('ec.table.name')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('ec.table.code')"
          prop="code"
          :rules="[
            {required: true, message: $t('ec.table.code') + $t('ec.table.codeEmpty'), trigger:'blur'},
            { validator: validateCode, trigger: 'blur' }
          ]"
        >
          <el-input
            v-model="formItem.code"
            type="text"
            :placeholder="$t('ec.table.code')"
          />
        </el-form-item>

        <!--        <el-form-item :label="$t('ec.tree.parent')" prop="parent.id">-->
        <!--          <span v-if="parent && parent.id">{{ parent.name }}</span>-->
        <!--          <ec-select-tree-->
        <!--            v-else-->
        <!--            ref="parentTree"-->
        <!--            v-model="formItem.parent.id"-->
        <!--            check-strictly-->
        <!--            url="api/v1/org/saasOrg/data"-->
        <!--            :data="{ tenantId: formItem.tenantId }"-->
        <!--            :params="{ excludeId: record.id }"-->
        <!--          />-->
        <!--        </el-form-item>-->

        <el-form-item
          :label="$t('ec.table.sort')"
          prop="sort"
          :rules="[
            {required: true, message: $t('ec.table.sort') + $t('ec.table.emptyError'), trigger:'blur'}
          ]"
        >
          <el-input-number
            v-model="formItem.sort"
            :placeholder="$t('ec.table.sort')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('ec.table.enableStatus')"
          prop="status"
          :rules="[
            {required: true, message: $t('ec.table.enableStatus') + $t('ec.table.emptyError'), trigger:'blur'}
          ]"
        >
          <ec-radio-group
            v-model="formItem.status"
            dict-type="enableState"
          />
        </el-form-item>
      </el-form>

      <section class="tab-btn">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addUser"
        >添加人员</el-button>
        <el-button
          type="success"
          @click="configData"
        >配置数据权限</el-button>
        <el-button
          type="warning"
          @click="configLocation"
        >配置位置权限</el-button>
      </section>

      <el-tabs
        stretch
        style="padding-left: 20px; padding-right: 10px;"
      >
        <el-tab-pane :label="dataMap.user">
          <vxe-grid
            ref="vxe"
            show-overflow
            show-header-overflow
            border
            highlight-hover-row
            class="vxe-table-element"
            resizable
            sync-resize
            auto-resize
            height="300px"
            :columns="userColumns"
            :data="formItem.sysrUserList"
          >
            <template v-slot:org_operation="{ row, rowIndex }">
              <el-button
                type="text"
                @click="setUserLocation(row)"
              >{{ $t('ec.table.positionPermission') }}</el-button>
              <el-button
                type="text"
                class="text-red-color"
                @click="deleteById('user', row.id, rowIndex)"
              >{{ $t('ec.table.del') }}</el-button>
            </template>
          </vxe-grid>
        </el-tab-pane>
        <el-tab-pane :label="dataMap.section">
          <vxe-grid
            ref="vxe"
            show-overflow
            show-header-overflow
            border
            highlight-hover-row
            class="vxe-table-element"
            resizable
            sync-resize
            auto-resize
            max-height="300px"
            :columns="sectionColumns"
            :data="formItem.sectionList"
          >
            <template v-slot:org_operation="{ row, rowIndex }">
              <el-button
                type="text"
                class="text-red-color"
                @click="deleteById('section', row.id, rowIndex)"
              >{{ $t('ec.table.del') }}</el-button>
            </template>
          </vxe-grid>
        </el-tab-pane>
        <el-tab-pane :label="dataMap.station">
          <vxe-grid
            ref="vxe"
            show-overflow
            show-header-overflow
            border
            highlight-hover-row
            max-height="300px"
            class="vxe-table-element"
            resizable
            sync-resize
            auto-resize
            :columns="stationColumns"
            :data="formItem.stationList"
          >
            <template v-slot:org_operation="{ row, rowIndex }">
              <el-button
                type="text"
                class="text-red-color"
                @click="deleteById('station', row.id, rowIndex)"
              >{{ $t('ec.table.del') }}</el-button>
            </template>
          </vxe-grid>
        </el-tab-pane>
        <el-tab-pane :label="dataMap.gantry">
          <vxe-grid
            ref="vxe"
            show-overflow
            show-header-overflow
            border
            highlight-hover-row
            max-height="300px"
            class="vxe-table-element"
            resizable
            sync-resize
            auto-resize
            :columns="gantryColumns"
            :data="formItem.gantryList"
          >
            <template v-slot:org_operation="{ row, rowIndex }">
              <el-button
                type="text"
                class="text-red-color"
                @click="deleteById('gantry', row.id, rowIndex)"
              >{{ $t('ec.table.del') }}</el-button>
            </template>
          </vxe-grid>
        </el-tab-pane>
        <el-tab-pane :label="dataMap.location">
          <vxe-grid
            ref="vxe"
            show-overflow
            show-header-overflow
            border
            highlight-hover-row
            max-height="300px"
            class="vxe-table-element"
            resizable
            sync-resize
            auto-resize
            :columns="locationColumns"
            :data="formItem.locationList"
          >
            <template v-slot:org_operation="{ row, rowIndex }">
              <el-button
                type="text"
                class="text-red-color"
                @click="deleteById('location', row.id, rowIndex)"
              >{{ $t('ec.table.del') }}</el-button>
            </template>
          </vxe-grid>
        </el-tab-pane>
      </el-tabs>

      <footer class="submit">
        <el-button
          v-if="method !== 'view'"
          style="width: 90px"
          type="primary"
          :loading="confirmLoading"
          @click="save"
        >{{ $t('ec.table.confirm') }}</el-button>
        <el-button
          style="width: 90px"
          @click="visible = false"
        >{{ $t('ec.table.close') }}</el-button>
      </footer>
    </el-drawer>
    <template v-if="visible">
      <data-view
        ref="dataViewVue"
        @getData="getDataViewData"
      />
      <add-user-view ref="addUserView" />
      <ec-contact
        ref="ecUser"
        multiple
        @getContact="getContact"
        :tenantId="formItem.tenantId"
        :initChoosedUsers="formItem.sysrUserList"
      />
      <OrgLocation
        ref="orgLocation"
        :org-locations="formItem.locationList"
        @change="getLocationData"
      />
      <userLocation ref="userLocation" />
    </template>
  </div>
</template>

<script>
import mixin from 'ecip-web/utils/common-mixin'
import { save, update, getMessage } from 'ecip-web/api/vue/org/baseOrgApi'
import Vue from 'vue'
import { cloneDeep } from 'ecip-web/utils'
import dataView from './dataView'
import addUserView from './addUserView'
import OrgLocation from './orgLocation'
import userLocation from '../../../user/sysrUser/components/userLocation'

export default {
  name: 'VueOrgBaseOrgForm',
  components: { dataView, addUserView, OrgLocation, userLocation },
  mixins: [...mixin],
  data() {
    return {
      visible: false,
      loading: false,
      confirmLoading: false,
      method: '',
      title: '租户组织机构',
      record: {},
      parent: {},
      formItem: {
        id: '',
        tenantId: '',
        name: '',
        code: '',
        orgType: '',
        sort: 30,
        status: '1',
        parent: {},
        userRatio: '',
        sectionNum: '',
        stationNum: '',
        gantryNum: '',
        locationNum: '',
        sysrUserList: [],
        sectionList: [],
        stationList: [],
        gantryList: [],
        locationList: []
      },
      dataMap: {
        user: '',
        section: '',
        station: '',
        gantry: '',
        location: ''
      },
      userColumns: [
        {
          title: 'ec.user.userName',
          field: 'username',
          minWidth: 150,
          sortable: true
        },
        {
          title: 'ec.user.realName',
          field: 'realName',
          minWidth: 150,
          sortable: true
        },
        {
          title: 'ec.sms.phone',
          field: 'phone',
          minWidth: 120,
          sortable: true
        },
        {
          title: 'ec.user.sex',
          field: 'sex',
          minWidth: 100,
          formatter: ['dict', 'sex']
        },
        { title: 'ec.email.address', field: 'email', minWidth: 100 },
        {
          title: 'ec.table.createDate',
          field: 'createTime',
          minWidth: 150,
          sortable: true
        },
        {
          title: 'ec.table.actions',
          width: 120,
          fixed: 'right',
          align: 'center',
          slots: { default: 'org_operation' }
        }
      ],
      sectionColumns: [
        { title: '收费路段名称', key: 'name', field: 'name' },
        { title: '收费路段编号', key: 'id', field: 'id' },
        {
          title: 'ec.table.actions',
          width: 80,
          fixed: 'right',
          align: 'center',
          slots: { default: 'org_operation' }
        }
      ],
      stationColumns: [
        { title: '收费站名称', key: 'name', field: 'name' },
        { title: '收费站编号', key: 'id', field: 'id' },
        {
          title: 'ec.table.actions',
          width: 80,
          fixed: 'right',
          align: 'center',
          slots: { default: 'org_operation' }
        }
      ],
      gantryColumns: [
        { title: '收费门架名称', key: 'name', field: 'name' },
        { title: '收费门架编号', key: 'id', field: 'id' },
        {
          title: 'ec.table.actions',
          width: 80,
          fixed: 'right',
          align: 'center',
          slots: { default: 'org_operation' }
        }
      ],
      locationColumns: [
        { title: '名称', key: 'name', field: 'name' },
        { title: '编号', key: 'id', field: 'id' },
        {
          title: 'ec.table.actions',
          width: 80,
          fixed: 'right',
          align: 'center',
          slots: { default: 'org_operation' }
        }
      ]
    }
  },
  watch: {},
  methods: {
    init(method, tenantId, row, parent) {
      this.parent = parent || {}
      this.method = method
      this.record = row
      this.formItem.tenantId = tenantId
      this.visible = true
      this.loading = false
      this.$nextTick(async () => {
        // 清空初始化
        this.$refs.form.clearValidate()
        this.$refs.form.resetFields()
        Object.assign(this.$data.formItem, this.$options.data().formItem)
        this.dataMap.user = '机构成员'
        this.dataMap.section = '收费路段'
        this.dataMap.station = '收费站'
        this.dataMap.gantry = '收费门架'
        this.dataMap.location = '位置点'
        if (method === 'edit' || method === 'view') {
          // 修改或者查看
          try {
            this.loading = true
            const { data } = await getMessage(row.tenantId, row.id)
            // this.formItem = data
            cloneDeep(this.formItem, data)
            Vue.set(this.formItem, 'parent', {
              id: this.formItem.parentId,
              name: this.formItem.parentName
            })
            this.dataMap.user = '机构成员(' + this.formItem.userRatio + ')'
            this.dataMap.section = '收费路段(' + this.formItem.sectionNum + ')'
            this.dataMap.station = '收费站(' + this.formItem.stationNum + ')'
            this.dataMap.gantry = '收费门架(' + this.formItem.gantryNum + ')'
            this.dataMap.location = `位置点(${this.formItem.locationNum})`
          } finally {
            this.loading = false
          }
        }
      })
    },
    // async validateCode(rule, value, callback) {
    //   const { data } = await checkCode((this.record && this.record.id) || '', value, this.formItem.tenantId)
    //   if (data.valid) {
    //     callback()
    //   } else {
    //     callback(new Error(this.$t('ec.table.code') + this.$t('ec.table.exist')))
    //   }
    // },
    setUserLocation(row) {
      this.$refs.userLocation.init(row)
    },
    save() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.formItem.parentId = this.formItem.parent.id
            this.confirmLoading = true
            const p = {
              gantryList: [],
              locationList: [],
              sectionList: [],
              stationList: [],
              sysrUserList: []
            }
            for (const key in p) {
              if (this.formItem[key].length) {
                p[key] = this.formItem[key].map((item) => {
                  return { id: item.id }
                })
              }
            }
            if (this.method === 'edit') {
              await update(Object.assign({}, this.formItem, p))
            } else {
              await save(Object.assign({}, this.formItem, p))
            }
            this.$notify.success(this.$t('ec.message.saveSuccess'))
            this.$emit('refreshData')
            this.visible = false
          } finally {
            this.confirmLoading = false
          }
        }
      })
    },
    deleteById(flag, id, rowIndex) {
      this.$confirm(
        this.$t('ec.message.delConfirm'),
        this.$t('ec.message.prompt'),
        {
          confirmButtonText: this.$t('ec.message.confirm'),
          cancelButtonText: this.$t('ec.message.cancel'),
          type: 'warning'
        }
      ).then(() => {
        // let index
        switch (flag) {
          case 'user':
            // index = this.formItem.sysrUserList.indexOf(id)
            this.formItem.sysrUserList.splice(rowIndex, 1)
            break
          case 'section':
            // index = this.formItem.sectionList.indexOf(id)
            this.formItem.sectionList.splice(rowIndex, 1)
            break
          case 'station':
            // index = this.formItem.stationList.indexOf(id)
            this.formItem.stationList.splice(rowIndex, 1)
            break
          case 'gantry':
            // index = this.formItem.gantryList.indexOf(id)
            this.formItem.gantryList.splice(rowIndex, 1)
            break
          case 'location':
            // index = this.formItem.gantryList.indexOf(id)
            this.formItem.locationList.splice(rowIndex, 1)
            break
        }
      })
    },
    addUser() {
      // 添加成员
      this.$refs.ecUser.visible = true
    },
    getContact(item) {
      this.formItem.sysrUserList = []
      item.userDetailList.forEach((child) => {
        const idx = this.formItem.sysrUserList.findIndex(
          (user) => user.id === child.id
        )
        if (idx === -1) {
          this.formItem.sysrUserList.push(child)
        }
      })
      this.formItem.sysrUserList = this.uniqueFunc(
        this.formItem.sysrUserList,
        'id'
      )
    },
    uniqueFunc(arr) {
      const res = new Map()
      return arr.filter(
        (item) => !res.has(item['id']) && res.set(item['id'], 1)
      )
    },
    async configData() {
      // 配置数据权限(查询收费路段、收费站、收费门架)
      /* await getSectionListByTenantId({ tenantId: this.formItem.tenantId }).then(function (result) {
        allSections = result.data
      })*/
      this.$refs.dataViewVue.init(
        this.formItem.tenantId,
        this.formItem.sectionList,
        this.formItem.stationList,
        this.formItem.gantryList
      )
    },
    getDataViewData(item) {
      this.formItem[item.type] = item.data
      // item.data.forEach((child) => {
      //   const idx = this.formItem[item.type].findIndex(user => user.id === child.id)
      //   if (idx === -1) {
      //     this.formItem[item.type].push(child)
      //   }
      // })
    },
    configLocation() {
      // 配置位置权限
      if (this.formItem.tenantId) {
        this.$refs.orgLocation.visible = true
        this.$refs.orgLocation.init(this.formItem)
      } else {
        this.$notify.warning('请选择租户')
      }
    },
    getLocationData(array) {
      this.formItem.locationList = array
      console.log(this.formItem)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .tab-btn {
    padding-left: 20px;
  }
  ::v-deep .el-drawer__header {
    margin-bottom: 10px;
    padding-top: 10px;
  }
  ::v-deep .el-drawer__body {
    overflow: auto;
    padding-bottom: 30px;
  }
  ::v-deep .el-form-item {
    margin-bottom: 14px;
  }
  .submit {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 15px;
  }
}
</style>
