<template>
  <div>
    <up-down-layout :header="$t('projectCompany.title')"
                 :handleFlag.sync="handleFlag">
      <search-form @handleFilter="handleFilter"
                   @clearParam="clearParam"
                   :formValue.sync="queryParas"
                   v-model="queryParas"
                   searchPerms="search"
                   :componentList="formtList"
                   slot="query"></search-form>
      <data-table :api="api"
                  :columns="columns"
                  :queryParas="queryParas"
                  :operateBtnLayout="operateBtnLayout"
                  :sourceData.sync="sourceData"
                  :menuFlag="true"
                  :headTitle="$t('projectCompany.title')"
                  :loadCount.sync="loadCount"
                  slot="table">
        <template slot="headButton">
          <div class="headButton">
<!--            <btn-download size="medium"-->
<!--                          type="primary"-->
<!--                          :fileID="queryParamscode"-->
<!--                          :classType="true"-->
<!--                          :downloadButtonMsg="$t('projectCompany.downloadmeun')"-->
<!--                          @beforeDownload="beforeDownload"></btn-download>-->
            <!--模板文件下载-->
            <auth-button size="medium" type="primary"
                         :label="$t('projectCompany.downloadmeun')"
                         :icon="'iconfont iconycxiazai'"
                         :loading="downloadFileByTemplateCodeLoading"
                         @click="downloadFileByTemplateCode"></auth-button>
            <!-- 文件上传 -->
            <btn-upload :store="$store"
                        btnSize="medium"
                        :btnDisplay="true"
                        perms="import_refunds"
                        :uploadName="$t('projectCompany.inport')"
                        :uploadApi="uploadApi"
                        @uploadSuccess="uploadSuccess"
                        type="primary"
                        class="marginleft10">
            </btn-upload >
            <!-- 文件上传 -->
            <!-- <upload-button :icon="'iconfont iconimport'"
                          btnSize="small"
                          :btnDisplay="true"
                          :uploadName="$t('projectCompany.inport')"
                          @uploadSuccess="uploadSuccess"
                          type="primary">
            </upload-button > -->
            <!-- <import-button btnSize="medium"
                          :btnDisplay="true"
                          type="primary"
                          @importSuccess="importSuccess"
                          @beforeUpload="beforeUpload"
                          :icon="'iconfont iconimport'"
                          :uploadName="$t('projectCompany.inport')">
                          </import-button> -->
          </div>
        </template>
        <template slot="enterpriseName" slot-scope="scope">
          <div class="over_box">
            <p v-for="(item, index) in scope.data.row.projectCompanyDTOList"
              class="no_top_bottom"
              :key="index">
              <span v-show="index < listLength ||
                    scope.data.row.isMore">{{item.enterpriseName}}</span>
            </p>
            <span v-if="scope.data.row.projectCompanyDTOList && scope.data.row.projectCompanyDTOList.length > listLength"
                  @click="showComanyMore(scope.data.row, scope.data.$index)"
                  class="view_more"> {{scope.data.row.isMore ? $t('projectCompany.packUp'): $t('projectCompany.viewMore')}}</span>
          </div>
        </template>
        <template slot="enabled" slot-scope="scope">
          <span>{{scope.data.row.enabled | formatDict}}</span>
        </template>
        <el-table-column :label="$t('common.operate')"
                         width="320"
                         align="center">
          <template slot-scope="scope">
            <auth-button size="small"
                         :title="$t('projectCompany.editxmgs')"
                         :icon="'iconfont iconcompanylist'"
                         class="iconCircle"
                         @click="showView(scope.row)"></auth-button>
            <auth-button size="small"
                         v-if="scope.row.projectCompanyDTOList.length !== 0"
                         v-show="scope.row.enabled === '0'"
                         :title="$t('projectCompany.open')"
                         :icon="'iconfont iconenable'"
                         class="iconCircle"
                         @click="enableStatus(scope.row , 1)"></auth-button>
            <auth-button size="small"
                         v-if="scope.row.projectCompanyDTOList.length !== 0"
                         v-show="scope.row.enabled === '1'"
                         :title="$t('projectCompany.close')"
                         :icon="'iconfont iconjinyong'"
                         class="iconCircle"
                         @click="enableStatus(scope.row, 0)"></auth-button>
          </template>
        </el-table-column>
      </data-table>
    </up-down-layout>
    <company-more :visible.sync="itemMoreVisible"
                  :dialogTitle="$t('projectCompany.enterpriseName')"
                  editModel="V"
                  :form="companyItems"></company-more>
    <project-company-list-view :visible.sync="viewListVisable"
                               :title="$t('projectCompany.viewtitle')"
                               @refresh="handleFilter"
                               editModel="E"
                               :form="viewItems"></project-company-list-view>
    <project-company-import-edit :visible.sync="importVisable"
                                 :dialogTitle="$t('projectCompany.importResultView')"
                                 editModel="V"
                                 :form="importItem"></project-company-import-edit>

  </div>

</template>
<script>
import { upDownLayout, DataTable, searchForm, btnUpload, btnDownload, authButton } from 'newepoch-components'
import BasePage from '@/pages/projectCompany/projectCompanyBasepage'
import companyMore from '@/pages/projectCompany/projectCompanyMoreList'
import projectCompanyListView from '@/pages/projectCompany/projectCompanyListView'
import projectCompanyImportEdit from '@/pages/projectCompany/projectCompanyImportEdit'
import API from '@/api/projectCompanyApi'
import * as format from '@/filters/index'
import SelectEnterprise from '@/components/element/zhunru/SelectEnterprise'
import { UPLOAD_API } from '@/constant'
import fileApi from '@/api/fileApi'
import { downFile } from '@/utils/devUtils'
export default {
  extends: new BasePage(),
  name: 'projectCompanyAdmitList',
  components: {
    btnUpload,
    btnDownload,
    authButton,
    upDownLayout,
    DataTable,
    searchForm,
    companyMore,
    projectCompanyImportEdit,
    projectCompanyListView
  },
  computed: {
    api () {
      return API.projectcompany
    },
    otherApi () {
      return API.AdmitModel
    }
  },
  mounted () {
    // todo 因加载字典问题需要在刷新时定成常量
    // this.maxShowNums = format.formatDict('companyheight', 'M0003') === 'companyheight' ? 30 : format.formatDict('companyheight', 'M0003') === 'companyheight'
    this.queryParamscode = format.formatDict('company', 'M0002') === 'company' ? '' : format.formatDict('company', 'M0002')
    this.listLength = format.formatDict('companyListSize', 'M0003') === 'companyListSize' ? 10 : format.formatDict('companyListSize', 'M0003')
  },
  methods: {
    downloadFileByTemplateCode () {
      this.downloadFileByTemplateCodeLoading = true
      fileApi.file.downloadFileByTemplateCode({ templateCode: 'company' }).then(res => {
        downFile(res)
      }).finally(res => {
        this.downloadFileByTemplateCodeLoading = false
      })
    },
    enableStatus (item, status) {
      let $this = this
      const { coreEnterpriseId } = item
      let obj = { coreEnterpriseId, enabled: status }
      this.otherApi.enabled(obj).then(res => {
        if (status === 0) {
          $this.$confirm('是否禁用？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            $this.handleFilter()
            $this.$message({
              type: 'success',
              message: '操作成功!'
            })
          }).catch(() => {
            $this.$message({
              type: 'info',
              message: '取消操作'
            })
          })
        } else {
          $this.handleFilter()
          $this.$message({
            type: 'success',
            message: '操作成功!'
          })
        }
      })
    },
    importSearch (list) {
      let $this = this
      this.otherApi
        .importSearch(list)
        .then(res => {
          $this.importVisable = true
          $this.importItem = res && res.data
        })
        .catch(e => {
          console.log(e)
        })
    },
    showView (item) {
      this.viewListVisable = true
      this.viewItems = item
    },
    showComanyMore (item, index) {
      const { isMore } = item
      this.$set(this.sourceData[index], 'isMore', !isMore)
    },
    importSuccess (data) {
      const [first, second, ...rest] = data
      if (!data.length) {
        return this.warning('请确认导入模板是否正确')
      }
      if ((!second && second.length !== 2) || !second.includes('核心企业名称') || !second.includes('项目公司') || !first || !first.length || !first.includes('项目公司准入导入模板')) {
        return this.warning('请确认导入模板是否正确')
      }
      if (!rest || !rest.length) {
        return this.warning('数据为空')
      }
      let postList = []
      rest.forEach(item => {
        let obj = {
          coreEnterpriseName: item[0],
          enterpriseName: item[1]
        }
        obj.fileId = this.fileId
        postList.push(obj)
      })
      this.importSearch(postList)
    },
    // 文件上传成功回调
    uploadSuccess (returnData, rowData, fileList) {
      let $this = this
      $this.fileId = returnData.fileID
      let index = fileList.length - 1
      let fm = new FormData()
      fm.append('file', fileList[index].raw)
      fileApi.file.importFile(fm).then(res => {
        if (res.success) {
          this.importSuccess(res.data)
        } else {
          $this.error('解析文件失败')
        }
      })
    },
    beforeDownload () {
      this.queryParamscode = format.formatDict('company', 'M0002')
    }
  },
  filters: {
    formatDict (val) {
      return format.formatDict(val, 'M0001')
    }
  },
  data () {
    const { common } = this.$i18n.messages[this.$i18n.locale]
    return {
      downloadFileByTemplateCodeLoading: false,
      fileId: '',
      uploadApi: UPLOAD_API,
      operateBtnLayout: '',
      itemMoreVisible: false,
      viewListVisable: false,
      importVisable: false,
      companyItems: {},
      viewItems: {},
      importItem: {},
      handleFlag: true,
      batchPackingLoading: false,
      queryParas: {},
      listLength: 0,
      maxShowNums: 10,
      sourceData: [],
      queryParamscode: '',
      queryParams: {},
      formtList: [
        {
          label: this.$i18n.messages[this.$i18n.locale].projectCompany
            .coreEnterprise,
          disabled: false,
          value: 'coreEnterpriseId',
          multiple: false,
          labelWidth: '70px',
          componentName: SelectEnterprise,
          store: this.$store
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].projectCompany.enabled,
          disabled: false,
          value: 'enabled',
          multiple: false,
          dictTypeCode: 'M0001',
          componentName: 'SelectDictionary',
          store: this.$store,
          labelWidth: '50px'
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].projectCompany
            .enterpriseName,
          disabled: false,
          value: 'enterpriseName',
          placeholder: common.input,
          multiple: false,
          labelWidth: '105px',
          componentName: 'el-input'
        }
      ],
      columns: [
        // 核心企业
        {
          prop: 'coreEnterpriseName',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].projectCompany
            .coreEnterprise,
          width: '20px'
        },
        // 项目公司名称
        {
          prop: 'enterpriseName',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].projectCompany.enterpriseName,
          slot: true
        },
        // 状态
        {
          prop: 'enabled',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].projectCompany.enabled,
          width: '20px',
          slot: true
        }
      ]
    }
  }
}
</script>
<style lang="scss" scoped>
  @import '~@/styles/projectCompany/projectCompanyAdmitList.scss';
</style>
