<template>
  <div>
    <dialog-edit :visible.sync="dialogVisible"
                 width="1480px"
                 :form="form"
                 :title="title"
                 :api="api"
                 :footerVisible="true"
                 :footerBtnShow="false"
                 :editModel="editModel">
      <div class="result-box">
        <search-form @handleFilter="handleFilter"
                     @clearParam="clearParam"
                     :formValue.sync="queryParas"
                     v-model="queryParas"
                     searchPerms="search"
                     :componentList="formtList"
                     :isShowFoldBtn="false"
                     slot="query">
        </search-form>
        <data-table :api="api"
                    :showPage="false"
                    :showSelection="true"
                    :columns="columns"
                    :selectedRows.sync="selectedRows"
                    :queryParas="queryParas"
                    :operateBtnLayout="operateBtnLayout"
                    :sourceData.sync="sourceData"
                    :menuFlag="false"
                    :headTitle="$t('projectCompany.editTitle')"
                    :loadCount.sync="loadCount"
                    slot="table">
          <template slot="headButton">
            <div class="headButton">
              <auth-button size="medium"
                           type="primary"
                           :icon="'iconfont iconxinzeng'"
                           @click="getCompany()"
                           :label="$t('common.create')">
              </auth-button>
              <auth-button size="medium"
                           type="danger"
                           :icon="'iconfont iconshanchu'"
                           @click="delCompanyItem()"
                           :label="$t('common.del')">
              </auth-button>
            </div>
          </template>
          <el-table-column :label="$t('projectCompany.enterpriseName')"
                           align="left"
                           header-align="center">
            <template slot-scope="scope">
              <template v-if="scope.row.edit">
                <el-form ref="ruleForm">
                  <el-form-item :prop="'sourceData.' + scope.$index + '.enterpriseId'">
                    <el-select v-model="scope.row.enterpriseId"
                               filterable
                               placeholder="请选择">
                      <el-option v-for="(item) in filterLits(scope.row.enterpriseId)"
                                 :key="item.enterpriseId"
                                 :label="item.enterpriseName"
                                 :value="item.enterpriseId" />
                    </el-select>
                  </el-form-item>
                </el-form>
              </template>
              <span v-else>{{scope.row.enterpriseName}}</span>
            </template>
          </el-table-column>
          <div slot="paginationLeft">
            <span>显示第{{endNum && '1' || 0}}至{{this.endNum}}项，共{{this.endNum}}项</span>
          </div>
        </data-table>
      </div>
      <div class="edit_footer" slot="footer">
        <auth-button size=""
                    type="primary"
                    @click="onSaved()"
                    :label="$t('projectCompany.btnDone')">
        </auth-button>
        <auth-button size=""
                    @click="close"
                    :label="$t('common.cancel')">
        </auth-button>
      </div>
    </dialog-edit>
  </div>
</template>

<script>
import BaseEdit from '@/pages/projectCompany/projectCompanyEditPage'
// import SearchForm from '@/components/element/searchForm'
// import DataTable from '@/components/element/DataTable'
import { DialogEdit, DataTable, searchForm, authButton } from 'newepoch-components'
// import AuthButton from '@/components/auth/authButton'
import API from '@/api/projectCompanyApi'
import { setTimeout } from 'timers'
export default {
  extends: new BaseEdit(''),
  components: { DialogEdit, searchForm, DataTable, authButton },
  props: {
    title: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      queryParas: {},
      newCompanys: [],
      editList: [],
      selectedRows: [],
      delListcompany: [],
      parentId: '',
      formtList: [
        {
          label: this.$i18n.messages[this.$i18n.locale].projectCompany
            .coreEnterprise,
          disabled: true,
          value: 'coreEnterprise',
          placeholder: '请输入',
          multiple: true,
          labelWidth: '70px',
          componentName: 'el-input'
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].projectCompany
            .enterpriseName,
          disabled: false,
          value: 'enterpriseName',
          placeholder: '请输入',
          multiple: true,
          labelWidth: '105px',
          componentName: 'el-input'
        }
      ],
      operateBtnLayout: '',
      sourceData: [],
      loadCount: 0,
      columns: []
    }
  },
  methods: {
    async handleFilter () {
      let { data: newData } = await this.api.projectcompanyList(this.queryParas)

      this.sourceData = newData
      this.newCompanys = []
      this.delListcompany = []
      // 去重
    },
    filterListObject (list, name) {
      let tempArray = []
      let hash = {}
      for (let i = 0; i < list.length; i++) {
        const itemName = list[i][name]
        if (!hash[itemName]) {
          tempArray.push(list[i])
          hash[itemName] = true
        }
      }
      return tempArray
    },
    close () {
      this.dialogVisible = false
    },
    filterLits (id) {
      if (!this.curretNewcompany.length) {
        return []
      }
      let tempList = []
      this.curretNewcompany.forEach(item => {
        const { enterpriseId } = item
        if (
          this.checkedIds.indexOf(enterpriseId) === -1 ||
          id === enterpriseId
        ) {
          tempList.push(item)
        }
      })
      return tempList
    },
    onSaved () {
      // 判断是否有新增未选择的数据
      if (this.checkedIds.length && this.checkedIds.indexOf('') > -1) {
        return this.warning('请先选择已添加的数据')
      }
      // 新增数据的数据格式处理
      let newAddlist = []
      let dellist = []
      this.sourceData.forEach(item => {
        const { edit, enterpriseId } = item
        if (edit && enterpriseId) {
          let now = this.curretNewcompany.filter(
            i => i.enterpriseId === enterpriseId
          )
          const { enterpriseName, keyId } = now[0]
          item.enterpriseName = enterpriseName
          if (keyId) {
            item.keyId = keyId
          }
        }
        edit && delete item.edit
        item.delStatus = '0'
        enterpriseId && newAddlist.push(item)
      })
      let sourceIds = this.sourceData.map(item => item.enterpriseId)

      this.delListcompany.forEach(item => {
        item.delStatus = '1'
        if (sourceIds.indexOf(item.enterpriseId) === -1) {
          dellist.push(item)
        }
      })
      let obj = Object.create(null)
      obj = {
        coreEnterpriseId: this.parentId,
        coreEnterpriseName: this.parentName,
        projectCompanyDTOList: [...newAddlist, ...dellist]
      }
      let $this = this
      this.api.saveCompanyList(obj).then(res => {
        $this.success('更新成功！')
        setTimeout(() => {
          $this.close()
          $this.$emit('refresh')
        }, 300)
      })
    },
    clearParam () {
      this.queryParas = {
        coreEnterpriseId: this.parentId,
        coreEnterprise: this.parentName
      }
    },
    delCompanyItem () {
      if (!this.selectedRows.length) {
        return this.warning('请先选择要删除的数据')
      }
      this.$confirm('此操作会删除选中数据，是否继续？', '提示', {
        type: 'warning'
      }).then(() => {
        let ids = this.selectedRows.map(i => i.enterpriseId)
        let beforeDel = this.delListcompany
        let delids = this.delListcompany.map(i => i.enterpriseId)
        let newSourceData = []
        let delLists = []
        this.sourceData.forEach(item => {
          const { enterpriseId: id } = item
          if (id !== '') {
            if (ids.indexOf(id) > -1) {
              delids.indexOf(id) === -1 && delLists.push(item)
            } else {
              newSourceData.push(item)
            }
          }
        })
        this.sourceData = newSourceData
        // 处理删除列表数据
        this.delListcompany = this.filterListObject(
          [...delLists, ...beforeDel],
          'enterpriseId'
        )
        this.selectedRows = []
      })
    },
    // 获取未
    async getCompany () {
      if (!this.newCompanys.length) {
        // 获取新增公司数据
        const { data: list } = await this.api.getCompanyList(this.queryParas)
        this.newCompanys = list || []
      }
      // 设置新增公司数据 （拿到的数据和列表删除的数据组合在一起）
      // this.curretNewcompany = [...this.newCompanys, ...this.delListcompany]

      // 判断是否有新增未选择的数据
      if (this.checkedIds.length && this.checkedIds.indexOf('') > -1) {
        return this.warning('请先选择已添加的数据')
      }
      let newItem = {
        edit: true,
        delStatus: '0',
        enterpriseId: '',
        enterpriseName: ''
      }
      this.sourceData.unshift(newItem)
    }
  },
  watch: {
    visible (old) {
      if (old) {
        const { coreEnterpriseId, coreEnterpriseName } = this.form
        this.parentId = coreEnterpriseId
        this.parentName = coreEnterpriseName
        this.queryParas = {
          coreEnterpriseId,
          coreEnterprise: coreEnterpriseName
        }
        this.handleFilter()
      } else {
        this.sourceData = []
        this.newCompanys = []
      }
    }
  },
  computed: {
    curretNewcompany () {
      return this.filterListObject(
        [...this.newCompanys, ...this.delListcompany],
        'enterpriseId'
      )
    },
    api () {
      return API.AdmitModel
    },
    checkedIds () {
      let now = this.sourceData.filter(item => item.edit === true)
      return now.map(item => item.enterpriseId)
    },
    endNum () {
      return this.sourceData.length || 0
    }
  }
}
</script>
<style lang="scss" scoped>
  @import '~@/styles/projectCompany/projectCompanyListView.scss';
</style>
