<template>
  <div class="common-page-content">
    <div class="common-search-container" ref="contentPanel">
      <el-form
        ref="form"
        :model="searchForm"
        label-width="auto"
        label-position="right "
        :inline="true"
        type="flex"
        justify="left"
      >
        <el-form-item label="企业名称">
          <el-input
            size="small"
            v-model="searchForm.companyName"
            clearable
            placeholder="请输入企业名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="container-btn">
        <el-button
          size="small"
          icon="el-icon-search"
          type="danger"
          class="btn btn-plus"
          @click="handleSearch"
        >
          搜索
        </el-button>
        <el-button
          size="small"
          icon="el-icon-refresh-right"
          class="btn btn-plus"
          @click="clearSearchForm"
        >
          重置
        </el-button>
      </div>
    </div>
    <el-row
      class="common-table-container flex searchPanel"
      :style="SearchPanel"
    >
      <el-col :span="24" class="common-table-wrapper">
        <div class="common-btn-group">
          <!-- <el-button
            size="small"
            icon="el-icon-plus"
            type="primary"
            class="btn btn-plus"
            @click="handleAdd"
          >
            新增
          </el-button> -->
          <!-- <el-button
            size="small"
            slot="reference"
            icon="el-icon-delete"
            type="danger"
            class="btn btn-delete"
            @click="handleDelete"
          >
            {{ this.$t('common.delete') }}
          </el-button> -->
          <!-- <el-button
            size="small"
            icon="el-icon-bottom"
            type="primary"
            plain
            class="btn btn-plus"
          >
            导出数据
          </el-button> -->
          <!-- <el-button
            size="small"
            icon="el-icon-plus"
            type="primary"
            :loading="auditing"
            class="btn btn-plus"
            @click="handleAudit"
          >
            提交审核
          </el-button> -->
        </div>
        <!-- LJ：表格高度自适应需配合样式  btn-pagenation 有按钮有分页  btngroup只有按钮  pagenation只有分页 -->
        <div class="common-table-content btn-pagenation">
          <el-table
            :border="true"
            stripe
            fit
            size="mini"
            v-loading="tableLoading"
            height="100%"
            ref="multipleSelection"
            :data="tableData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" min-width="5%" align="center">
            </el-table-column>
            <el-table-column
              prop="companyCode"
              show-overflow-tooltip
              min-width="100px"
              align="center"
              label="企业编号"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="historyCompanyCode"
              min-width="100px"
              label="历史编号"
              align="center"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="companyName"
              min-width="130px"
              show-overflow-tooltip
              label="企业名称"
              align="center"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="companyOrgcode"
              min-width="140px"
              label="税号"
              show-overflow-tooltip
              align="center"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="companyEbe"
              min-width="120px"
              label="企业法人"
              show-overflow-tooltip
              align="center"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="companyContact"
              min-width="120px"
              label="企业联系人"
              show-overflow-tooltip
              align="center"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="contactTel"
              min-width="120px"
              label="联系方式"
              show-overflow-tooltip
              align="center"
              resizable
            >
            </el-table-column>
            <!-- <el-table-column min-width="170px" align="center" label="操作">
              <template v-slot="{row}">
                <div>
                  <el-button
                    icon="el-icon-upload2"
                    type="primary"
                    plain
                    size="small"
                    @click="handleOpen(row)"
                    >资质文件上传</el-button
                  >
                </div>
              </template> 
            </el-table-column> -->
          </el-table>
        </div>
        <div class="common-pagenation">
          <el-pagination
            ref="paginationPanel"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParam.pageBean.page"
            :page-sizes="[20, 30, 40, 50]"
            :page-size="queryParam.pageBean.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryParam.pageBean.total"
          >
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <!-- 审核记录 -->
    <el-dialog
      title="审核记录"
      :visible.sync="visible"
      width="60%"
      :before-close="dialogBeforeClose"
    >
      <el-table
        class="down"
        :data="authList"
        border
        stripe
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="reviewerName" label="审核人"></el-table-column>
        <el-table-column prop="reviewTime" label="审核时间"></el-table-column>
        <el-table-column prop="createTime" label="审核状态">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.reviewResult == 1"
              >通过</el-tag
            >
            <el-tag type="danger" v-if="scope.row.reviewResult == 0"
              >驳回</el-tag
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 资质附件上传 -->
    <el-dialog
      title="资质文件上传"
      :visible.sync="dialogVisible"
      width="70%"
      :close-on-click-modal="false"
      :before-close="cancelConfirm"
    >
      <el-form ref="formInfo" label-width="auto" label-position="right">
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">资质信息</div>
          </div>
        </div>

        <el-form
          ref="form"
          v-for="(item, index) in parameter.qualificationLabelList"
          :key="index"
          label-width="80px"
        >
          <el-form-item :label="item.qualificationCategoryName">
            <div style="text-align: left">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-plus"
                @click="addTable(item)"
                style="margin-left: 10px"
                >添加</el-button
              >
            </div>
          </el-form-item>
          <el-table
            class="down"
            :data="item.dataList"
            border
            stripe
            style="width: 100%; margin-top: 20px"
          >
            <!-- <el-table-column
              prop="qualificationTypeName"
              min-width="130px"
              label="资质分类"
            >
              <template slot-scope="scope">
                <el-input
                  disabled
                  v-model="scope.row.qualificationTypeName"
                  placeholder="请选择资质分类"
                >
                </el-input>
              </template>
            </el-table-column> -->
            <el-table-column prop="qualificationName" label="资质名称">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.qualificationName"
                  placeholder="请输入资质名称"
                >
                  <el-button
                    slot="append"
                    @click="openQualification(scope.row)"
                    class="searchBtn"
                    icon="el-icon-search"
                  ></el-button>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="qualificationAcquisitionDate"
              label="取得日期"
            >
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.qualificationAcquisitionDate"
                  type="date"
                  placeholder="请选择取得日期"
                  style="width: 100%"
                  clearable
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </template>
            </el-table-column>
            <el-table-column prop="expiryDate" label="到期日期">
              <template slot-scope="scope">
                <el-date-picker
                  style="width: 100%"
                  v-model="scope.row.expiryDate"
                  type="date"
                  placeholder="请选择到期日期"
                  clearable
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              show-overflow-tooltip
              label="文件名称"
            ></el-table-column>
            <el-table-column
              prop="createTime"
              show-overflow-tooltip
              label="上传时间"
            >
            </el-table-column>
            <el-table-column width="100px" label="附件">
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="text"
                  v-if="scope.row.accessoryList.length != 0"
                >
                  <a
                    target="_blank"
                    @click="downloadFile(scope.row.name, scope.row.url)"
                    >下载</a
                  >
                </el-button>
                <el-button
                  size="small"
                  v-if="scope.row.accessoryList.length != 0"
                  type="text"
                  @click="deleteHandle(scope.row, scope.$index)"
                  >删除</el-button
                >
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  :headers="headers"
                  v-else
                  :action="action"
                  :file-list="scope.row.accessoryList"
                  :multiple="true"
                  accept=".png,.jpg,.jpeg,.xlsx,.xls,.pdf,.docx,.doc,.zip,.rar"
                  :show-file-list="false"
                  :on-success="
                    (res) => {
                      return handleSuccess(res, scope.row, scope.$index)
                    }
                  "
                >
                  <el-button slot="trigger" size="small" type="primary"
                    >上传文件</el-button
                  >
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column width="120px" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  circle
                  class="closeBtn"
                  icon="el-icon-close"
                  @click="delTable(scope.row, scope.$index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancelConfirm()">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="submitImport"
          plain
          :loading="loadingBtn"
          element-loading-text="拼命导入中"
          v-loading.fullscreen.lock="fullscreenLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <qualificationDialog
      ref="qualification"
      :useOrgList="qualificationList"
      @load="getLoad"
    ></qualificationDialog>
  </div>
</template>

<script>
import supplierManger from '@/api/supplierManger.js'
import {mapState} from 'vuex'
import pagination from '@/components/pagination'
import {TableMixin} from '@/mixins/tableMixin'
import routerManagement from '@/api/BasicDataManagement/routerManagement.js'
import req from '@/request.js'
import qualificationDialog from '@/components/dialog/qualificationDialog.vue'
import utils from '@/utils.js'
import {file} from 'jszip'
export default {
  name: 'DemandEntry',
  components: {
    pagination,
    qualificationDialog
  },
  mixins: [TableMixin],
  data() {
    return {
      currentPage: 1,
      tableMaxHeight: 400,
      dialogVisible: false,
      auditing: false,
      loading: false,
      tableLoading: false,
      loadingBtn: false,
      visible: false,
      qualificationList: [],
      tableData: [],
      fullscreenLoading: false,
      multipleSelection: [],
      form: {},
      parameter:{
        qualificationLabelList: [],
      },
      suppliersQualificationList: [],
      index: null,
      queryParam: {
        pageBean: {
          page: 1,
          pageSize: 20,
          total: 0,
        },
        sorter:[{
          direction: 'DESC',
          property: 'companyCode',
        }]
      },
      searchForm: {
      
      }, // 顶部搜索对象
      authList: [],
      deleteIds: '', // 是否选中列表解锁删除按钮
      fileList: [], // 文件上传
      edit: false, // 是否是修改功能
      currentDataDel: [], // 删除时排查是否有在审核的数据
    }
  },
  created() {
    this.handleSearch()
  },
  methods: {
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
      if (this.multipleSelection.length > 1) {
        this.$refs.multipleSelection.toggleRowSelection(
          this.multipleSelection[0],
          false
        )
      }
    },
    getDictName(code, value) {
      return utils.getDictName(code, value)
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用,function(file, fileList)
    handleSuccess(res, val) {
      console.log(res, 'resss', val)
      this.form.suppliersQualificationList.forEach((item, index) => {
        if (index == this.index) {
          item.accessoryList.push(res.value)
          item.filename = res.value.name
          item.filetime = res.value.createTime
          item.url = res.value.url
          item.fileList.forEach((e, n) => {
            item.accessoryList.forEach((i, v) => {
              if (n==this.index&&this.index == v) {
                let obj = {...e,...i}
                item.fileList.push(obj)
              }
            })
          })
        }
      })
      this.$forceUpdate()
      console.log(this.form.suppliersQualificationList, '11111111')
    },
    onExceed(file, fileList) {
      this.$message.error('超出最大可上传文件个数')
    },
    handleOpen(row) {
      console.log(row, 'row11')
      this.getById(row.id)
      this.dialogVisible = true
    },
    submitImport() {
      this.form.suppliersQualificationList.forEach((item) => {
        if (item.fileList.length != 0) {
          item.fileList.forEach((val) => {
            this.fileList.push(val)
          })
        }
      })
      this.fileList.forEach((item) => {
        if (item.id) {
          delete item.id
        }
      })
      let data = {
        id: this.form.id,
        fileList: this.fileList,
      }
      this.loadingBtn = true
      this.fullscreenLoading = true
      this.$http
        .post(
          '${portal}/supplier/bizSupplierEnterprise/v1/uploadAccessory',
          data
        )
        .then((res) => {
          this.loadingBtn = false
          this.fullscreenLoading = false
          if (res.data.state) {
            this.fileList = []
            this.$message.success(res.data.message)
          }
          this.dialogVisible = false
          this.handleSearch()
        })
    },
    openUpload(row, index) {
      this.index = index
      this.clickUpload(row, index)
    },
    clickUpload(row, index) {
      if (index == this.index) {
        this.$refs['upload'][index].$refs['upload-inner'].handleClick()
      }
    },
    //获取数据
    loadData() {
      this.tableLoading = true
      this.$http
        .post(
          '${portal}/enterprise/v1/queryAll',
          this.queryParam
        )
        .then((res) => {
          console.log(res,333333333);
          this.tableLoading = false
          const data = (res && res.data) || {}
          this.tableData = data.rows || []
          this.queryParam.pageBean = {
            page: data.page,
            pageSize: data.pageSize,
            total: data.total,
          }
        })
    },
    openQualification(row) {
      this.$refs.qualification.add(row)
    },
    // 上传附件成功回调
    handleSuccess(res, row, index) {
      row.accessoryList.push(res.value)
      let data = {...row, ...res.value}
      this.parameter.qualificationLabelList.forEach((item) => {
        item.dataList.forEach((val) => {
          if (val.key == data.key) {
            val['name'] = data.name
            val['createTime'] = data.createTime
            return val
          }
        })
      })
      this.$forceUpdate()
    },
    // 删除
    deleteHandle(row, index) {
      this.$confirm('是否确认删除该附件', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        row.accessoryList.splice(index, 1)
        row.name = ''
        row.fileTime = ''
        row.url = ''
        row.accessoryList = []
      })
    },
    addTable(item) {
      item.dataList.push({
        qualificationTypeName: item.qualificationCategoryName,
        qualificationTypeCode: item.qualificationCategoryCode,
        qualificationAcquisitionDate: '',
        expiryDate: '',
        accessoryList: [],
        key: Math.random() + '',
        qualificationForm: 1,
      })
    },
    submitImport() {
      this.loadingBtn = true
      let arr = []
      this.parameter.qualificationLabelList.forEach((item) => {
        item.dataList.forEach((val) => {
          if (val.key) {
            delete val.key
          }
          val.qualificationMemberId = this.form.qualificationMemberId
          val.qualificationMember = this.form.qualificationMember
          arr.push(val)
        })
      })
      this.form.qualificationLabelList = arr
      this.$http
        .post(
          '${portal}/supplier/bizSupplierEnterprise/v1/uploadAccessory',
          this.form
        )
        .then((res) => {
          console.log(res, 11111111)
          if (res.data.state) {
            this.loadData()
            this.dialogVisible = false
          }
          this.loadingBtn = false
        })
    },
    handleOpen(row) {
      this.form = row
      this.form.qualificationMember = row.supplierName
      this.form.qualificationMemberId = row.supplierId
      this.parameter.qualificationLabelList = row.suppliersQualificationList
      this.parameter.qualificationLabelList.forEach((item) => {
        this.$set(item, 'dataList', [])
        item.qualificationTypeName = item.qualificationCategoryName
      })
      this.dialogVisible = true
    },
    //列表删除行
    delTable(row, index) {
      this.parameter.qualificationLabelList.forEach((item, i) => {
        if (index == i) {
          item.dataList.splice(index, 1)
        }
      })
      this.$forceUpdate()
    },
    save() {
      this.parameter.qualificationLabelList.forEach((item, index) => {
        if (index == this.index) {
          this.multipleSelection.forEach((val) => {
            item.qualificationTypeName = val.name
            item.qualificationTypeCode = val.code
          })
        }
      })
      this.visible = false
    },
    //下载按钮回调
    downloadFile(name, url) {
      var a = document.createElement('a')
      var event = new MouseEvent('click')
      a.download = name
      a.target = '_blank'
      a.href = url
      a.dispatchEvent(event)
    },
    handleAudit() {
      if (this.fileList.length == 0) {
        this.$message.warning('请上传资质文件')
        return
      }
      this.auditing = true
      this.$http
        .post(
          '${portal}/supplier/bizSupplierEnterprise/v1/updateReviewStatus?id=' +
            this.multipleSelection[0].id +
            '&status=1&rejectionReason='
        )
        .then((res) => {
          if (res.data.state) {
            this.$message.success(res.data.message)
          }
          this.handleSearch()
          this.auditing = false
        })
    },
    getById(id) {
      this.$http
        .get('${portal}/supplier/bizSupplierEnterprise/v1/getById/' + id)
        .then((res) => {
          console.log(res, 'da')
          this.form = res.data
          this.form.suppliersQualificationList.forEach((item) => {
            this.$set(item, 'fileList', [])
            this.$set(item, 'accessoryList', [])
            item.fileList.push({
              qualificationCategoryName: item.qualificationCategoryName,
              qualificationCategoryId:item.qualificationCategoryId
            })
          })
          console.log(this.form.suppliersQualificationList)
          this.$forceUpdate()
        })
    },
    addList(row, idnex) {
      row.fileList.push({
        qualificationCategoryName: row.qualificationCategoryName,
      })
    },
    getLoad(data) {
      data.forEach((val) => {
        val.accessoryList = []
        this.parameter.qualificationLabelList.forEach((item) => {
          if (item.dataList.length&&val.qualificationTypeCode == item.qualificationCategoryCode) {
            item.dataList = data
          }
          this.$forceUpdate()
        })
      })
      this.$forceUpdate()
    },
    // 编辑
    handleEdit(rows) {
      this.$refs.form.clearValidate()
      this.$router.push({
        path: `/onboardingAddDialog/${rows.id}`,
        query: {pageBean: this.params},
      })
    },
    handleAdd(row) {
      let data = {
        row,
        form: 'supplier',
      }
      localStorage.setItem('dataKey', JSON.stringify(data))
      this.$router.push({
        path: `/supplierIssueList/${row.supplierId}/${row.enterpriseId}`,
        query: {data},
      })
    },
    // 详情
    handleDetail(rows) {
      this.$router.push({
        path: `/onboardingDetail/${rows.id}`,
        query: {pageBean: this.params},
      })
    },
    cancelConfirm() {
      this.fileList = []
      this.dialogVisible = false
    },
    //重置
    clearSearchForm() {
      this.searchForm = {
    
      }
      this.handleSearch()
    },
    //下载按钮回调
    downloadFile(name, url) {
      var a = document.createElement('a')
      var event = new MouseEvent('click')
      a.download = name
      a.target = '_blank'
      a.href = url
      a.dispatchEvent(event)
    },
    // 删除
    deleteHandle(row, index) {
      this.$confirm('是否确认删除该附件', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.form.suppliersQualificationList.forEach((item, index) => {
          item.fileList.forEach((val, i) => {
            if (index == i) {
              item.accessoryList.splice(i, 1)
              row.filename = ''
              row.filetime = ''
              row.url = ''
            }
          })
        })
      })
    },
    delTable(index, item) {
      item.fileList.splice(index, 1)
    },
    // 顶部搜索
    handleSearch() {
      let obj = this.searchForm
      let querys = []
      for (let i in obj) {
        if (obj[i]) {
          querys.push({
            group: 'main',
            operation:
              i == 'companyName' || i == 'enterprise_name_'
                ? 'LIKE'
                : 'EQUAL',
            parentGroup: '',
            property: i,
            relation: 'AND',
            value: obj[i],
          })
        }
      }

      this.queryParam.querys = querys
      this.loadData(this.queryParam)
    },
    handleCurrentChange(page) {
      this.queryParam.pageBean = {...this.queryParam.pageBean, page}
      this.loadData(this.queryParam)
    },
    handleSizeChange(pageSize) {
      this.queryParam.pageBean = {...this.queryParam.pageBean, pageSize}
      this.loadData(this.queryParam)
    },
    handleAuth(row) {
      let data = {
        querys: [
          {
            group: 'main',
            operation: 'EQUAL',
            parentGroup: '',
            property: 'admittedSupplierId',
            relation: 'AND',
            value: row.id,
          },
          {
            group: 'main',
            operation: 'EQUAL',
            parentGroup: '',
            property: 'type',
            relation: 'AND',
            value: 1,
          },
        ],
        pageBean: {
          page: -1,
          pageSize: -1,
        },
        sorter: [
          {
            direction: 'DESC',
            property: 'create_time_',
          },
        ],
      }
      this.$http
        .post('${portal}/supplierEnterpriseAuditing/v1/page', data)
        .then((res) => {
          this.authList = res.data.value.rows
          this.visible = true
        })
    },
    dialogBeforeClose() {
      this.visible = false
      this.dialogVisible = false
    },
  },
  computed: {
    ...mapState({
      headers: (state) => {
        return {Authorization: `Bearer ${state.login.currentUser.token}`}
      },
      action: function () {
        return window.context.portal + '/biz/universal/v1/minioUpload'
      },
    }),
    SearchPanel() {
      return {
        '--searchPanel': this.searchPanel + 'px',
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.cloumn-btn {
  border: 1px solid #2761ff;
  padding: 3px 10px;
  border-radius: 5px;
  &:nth-child(1) {
    margin-right: 5px;
  }
  &:nth-child(2) {
    margin-right: 5px;
  }
  &:nth-child(1):hover {
    background-color: #2761ff;
    color: #fff;
  }
  &:nth-child(2):hover {
    background-color: #2761ff;
    color: #fff;
  }
  /deep/ i,
  span {
    font-size: 16px;
  }
}
.dia-btn {
  width: 100% !important;
}
/deep/ .el-tree-node__content {
  padding: 5px 0;
}

/deep/ .el-table thead tr th {
  background-color: #eee !important;
  border-right: 1px solid #dfe2e8 !important;
}
/deep/ .el-table {
  border-collapse: collapse !important;
}
.iconBtn {
  border-color: none !important;
  width: 100% !important;
  border: 0px;
}
.closeBtn {
  font-size: 14px !important;
  /deep/.el-icon-close {
    font-size: 14px !important;
  }
}
</style>
