<template>
  <div class="edit-add-detail">
    <div class="crumbs">
      <Breadcrumb
        :breadcrumbOpt="breadcrumbOpt"
        svg-name="#icon-icon_analysis_patent"
        @breadcrumb-click="handleClose"
      />
    </div>
    <div class="form-content">
      <el-form
        ref="formInfo"
        :model="parameter"
        label-width="auto"
        label-position="right"
        :rules="rules"
      >
        <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-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="资质类型" prop="qualificationTypeName">
              <el-input
                v-model="parameter.qualificationTypeName"
                clearable
                @focus="handleOpen"
                placeholder="请选择资质类型"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资质编码" prop="qualificationCode">
              <el-input
                clearable
                v-model="parameter.qualificationCode"
                placeholder="请输入资质编码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="display: flex; flex-wrap: wrap">
          <el-col :span="12">
            <el-form-item label="资质名称" prop="qualificationName">
              <el-input
                clearable
                v-model="parameter.qualificationName"
                placeholder="请输入资质名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属权分类" prop="qualificationForm">
              <dict-select
                dictCode="zzly"
                :hasDefaultOption="true"
                clearable
                style="width: 100%"
                @select="changeForm"
                v-model="parameter.qualificationForm"
                placeholder="请选择所属权分类"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="parameter.qualificationForm == 1">
            <el-form-item label="资质所属权" prop="qualificationForm">
              <el-input
                disabled
                v-model="parameter.createName"
                placeholder="请输入"
              >
                <!-- <el-button slot="append" @click="openCompany" icon="el-icon-search"></el-button> -->
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="parameter.qualificationForm == 3">
            <el-form-item label="资质所属权" prop="qualificationForm">
              <el-input
                disabled
                v-model="parameter.createName"
                placeholder="请输入"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="有效开始期"
              prop="qualificationAcquisitionDate"
            >
              <el-date-picker
                clearable
                style="width: 100%"
                v-model="parameter.qualificationAcquisitionDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择有效开始期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效截止期" prop="expiryDate">
              <el-date-picker
                clearable
                style="width: 100%"
                v-if="parameter.qualificationForm == 1"
                v-model="parameter.expiryDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择有效截止期"
              >
              </el-date-picker>
              <el-select
                style="width: 100%"
                v-if="parameter.qualificationForm == 3"
                clearable
                v-model="parameter.expiryDate"
                placeholder="选择有效截止期"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.name"
                  @click.native="changeExpiryDate(item)"
                  :value="item.name"
                >
                </el-option>
                <el-option style="height: 100%;">
                  <template>
                    <el-date-picker
                      value-format="yyyy-MM-dd"
                      @change="changeDate"
                      v-model="parameter.expiryDate"
                      style="width: 100%; margin-top: 10px"
                      clearable
                      placeholder="请选择有效期至"
                    ></el-date-picker>
                  </template>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="创建人姓名" prop="createName">
              <el-input
                clearable
                v-model="parameter.createName"
                placeholder="请输入创建人姓名"
              ></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>
        <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-upload
          class="upload-demo"
          ref="upload"
          :headers="headers"
          :action="action"
          :file-list="dataList"
          :multiple="false"
          accept=".png,.jpg,.jpeg,.xlsx,.xls,.pdf,.docx,.doc,.zip,.rar"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="handleSuccess"
        >
          <el-button slot="trigger" size="small" type="primary"
            >上传文件</el-button
          >
        </el-upload>
        <el-table
          class="down"
          :data="dataList"
          border
          stripe
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column prop="name" label="文件名称"></el-table-column>
          <el-table-column prop="size" label="文件大小">
            <template slot-scope="scope">
              <span>{{ scope.row.fileSize }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="上传时间">
            <template slot-scope="scope">
              <div>
                {{ scope.row.createTime }}
              </div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="操作">
            <template slot-scope="scope">
              <el-button size="small" type="text">
                <a
                  target="_blank"
                  @click="downloadFile(scope.row.name, scope.row.url)"
                  >下载</a
                >
              </el-button>
              <el-button
                size="small"
                type="text"
                @click="deleteHandle(scope.$index, scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div slot="footer" class="footer">
      <el-button @click="handleClose">{{ $t('domestic.cancel') }}</el-button>
      <el-button type="primary" :loading="saveing" @click="handleSave">{{
        $t('domestic.save')
      }}</el-button>
    </div>
    <el-dialog
      title="资质类型"
      :visible.sync="dialogVisible"
      width="60%"
      v-loading="loading"
      :before-close="dialogBeforeClose"
    >
      <div>
        <div class="common-table-content btn-pagenation" ref="tableContent">
          <el-table
            :border="true"
            stripe
            fit
            size="mini"
            :max-height="tableHeight"
            ref="multipleSelection"
            :data="aptitudeList"
            @selection-change="selectChange"
          >
            <el-table-column type="selection" min-width="20%" align="center">
            </el-table-column>
            <el-table-column
              prop="code"
              min-width="10%"
              label="资质类型编码"
              align="center"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="name"
              show-overflow-tooltip
              min-width="10%"
              align="center"
              label="资质类型名称"
              resizable
            >
            </el-table-column>
          </el-table>
        </div>
        <!-- <div class="common-pagenation">
          <el-pagination
            ref="paginationPanel"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="params.pageBean.page"
            :page-sizes="[20, 30, 40, 50]"
            :page-size="params.pageBean.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="params.pageBean.total"
          >
          </el-pagination>
        </div> -->
      </div>
      <div slot="footer">
        <el-button @click="dialogBeforeClose">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <UnitList @addDetail="companyList" ref="unit" />
  </div>
</template>

<script>
import {mapState} from 'vuex'
import Breadcrumb from '@/components/Breadcrumb/index.vue'
import basicData from '@/api/basicData'
import UnitList from '@/components/dialog/UnitList'
import {Select} from 'element-ui'
export default {
  name: 'domesticDialog',
  components: {Breadcrumb, UnitList},
  props: {
    editData: Object,
  },
  data() {
    return {
      dataList: [],
      saveing: false,
      dialogVisible: false,
      loading: false,
      selectArr: [],
      options: [{id: 1, name: '永久', value: 1}],
      breadcrumbOpt: [{breadcrumbName: '资质管理'}, {breadcrumbName: '新增'}],
      rules: {
        qualificationCode: [
          {
            required: true,
            message: '请输入资质类型编码',
            trigger: 'blur',
          },
        ],
        qualificationTypeName: [
          {
            required: true,
            message: '请输入资质类型名称',
            trigger: 'blur',
          },
        ],
        qualificationName: [
          {
            required: true,
            message: '请输入资质名称',
            trigger: 'blur',
          },
        ],
        qualificationAcquisitionDate: [
          {
            required: true,
            message: '请选择取得日期',
            trigger: 'blur',
          },
        ],
        expiryDate: [
          {
            required: true,
            message: '请选择有效截止期',
            trigger: 'blur',
          },
        ],
        qualificationForm: [
          {
            required: true,
            message: '请输入选择资质来源',
            trigger: 'blur',
          },
        ],
      },
      parameter: {
        qualificationTypeValue: '',
        qualificationTypeName: '',
        qualificationCode: '',
        qualificationName: '',
        expiryDate: '',
        createName: '',
        qualificationAcquisitionDate: '',
        createBy: '',
        qualificationForm: 1,
        accessoryList: [],
        qualificationMember: '',
        qualificationMemberId: '',
      },
      aptitudeList: [],
    }
  },
  computed: {
    ...mapState({
      headers: (state) => {
        return {Authorization: `Bearer ${state.login.currentUser.token}`}
      },
      action: function () {
        return window.context.portal + '/biz/universal/v1/minioUpload'
      },
    }),
  },
  created() {
    this.addModifyBtn()
    this.currentUser = JSON.parse(sessionStorage.getItem('currentUserDetail'))
    this.parameter.createName = this.currentUser.org[0].orgName
    this.parameter.createBy = this.currentUser.org[0].orgId
    this.parameter.qualificationMemberId = this.currentUser.org[0].orgId
    this.parameter.qualificationMember = this.currentUser.org[0].orgName
    let moment = require('moment')
    this.parameter.qualificationAcquisitionDate = moment().format('YYYY-MM-DD')
    this.parameter.expiryDate = moment().format('YYYY-MM-DD')
  },
  mounted() {},
  methods: {
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用,function(file, fileList)
    handleSuccess(res, file, fileList) {
      console.log(res, fileList)
      this.dataList.push(res.value)
    },
    beforeUpload(file) {
      let acceptList = ['xlsx', 'xls','png','jpg','jpeg','xlsx','xls','pdf','docx','doc','zip','rar']
      // 根据文件名获取文件的后缀名
      let fileType = file.name.split('.').pop().toLowerCase()
      // 判断文件格式是否符合要求
      if (acceptList.indexOf(fileType) === -1) {
        this.$message.error('请上传 .png,.jpg,.jpeg,.xlsx,.xls,pdf,.docx,.doc,.zip,.rar 格式的文件 !')
        return false
      }
    },
    //下载按钮回调
    downloadFile(name, url) {
      console.log(name, 'name')
      var a = document.createElement('a')
      var event = new MouseEvent('click')
      a.download = name
      a.target = '_blank'
      a.href = url
      a.dispatchEvent(event)
    },
    changeDate(val) {
      this.parameter.expiryDate = val
      this.$forceUpdate()
    },
    changeExpiryDate(item) {
      this.parameter.expiryDate = item.name
    },
    // 删除
    deleteHandle(index, id) {
      this.$confirm('是否确认删除该附件', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (id) {
          this.$http
            .post('${portal}/biz/universal/v1/delete?ids=' + id)
            .then((res) => {
              if (res.data.state) {
                this.$message.success('删除成功')
                this.modifychoData(this.$route.query.editRows)
              }
            })
        } else {
          this.dataList.splice(index, 1)
        }
      })
    },
    //编辑
    addModifyBtn() {
      if (this.$route.query.editRows) {
        this.breadcrumbOpt[1].breadcrumbName = '编辑'
        this.modifychoData(this.$route.query.editRows)
      } else {
        this.breadcrumbOpt[1].breadcrumbName = '新增'
      }
    },
    //获取修改回显数据
    modifychoData(val) {
      this.$http
        .post('${portal}/bizQualificationLabel/v1/getById?id=' + val.id)
        .then((res) => {
          if (res.data.state) {
            this.parameter = res.data.value
            this.dataList = res.data.value.accessoryList
            this.parameter.createName = this.parameter.qualificationMember
          }
        })
    },
    changeForm(val) {
      if (val == 1) {
        this.parameter.createName = this.currentUser.org[0].orgName
        this.parameter.createBy = this.currentUser.org[0].orgId
        this.parameter.qualificationMemberId = this.currentUser.org[0].orgId
        this.parameter.qualificationMember = this.currentUser.org[0].orgName
      }
      if (val == 3) {
        this.parameter.createName = this.currentUser.user.fullname
        this.parameter.createBy = this.currentUser.user.userId
        this.parameter.qualificationMemberId = this.currentUser.user.userId
        this.parameter.qualificationMember = this.currentUser.user.fullname
      }
    },
    selectChange(val) {
      this.selectArr = val
      if (this.selectArr.length > 1) {
        this.$refs.multipleSelection.toggleRowSelection(
          this.selectArr[0],
          false
        )
      }
    },
    save() {
      this.parameter.qualificationTypeName = this.selectArr[0].name
      this.parameter.qualificationTypeCode = this.selectArr[0].code
      this.dialogBeforeClose()
    },
    // 关闭//面包屑点击
    handleClose() {
      if (this.breadcrumbOpt[1].breadcrumbName === '编辑') {
        this.$router.push({
          name: 'qualificationManagement',
          params: {
            tabsActiveName: 'libraryQualifications',
            pageBean: this.$route.query.pageBean,
          },
        })
      } else {
        this.$router.push({
          name: 'qualificationManagement',
          params: {
            tabsActiveName: 'libraryQualifications',
          },
        })
      }
      this.parameter = {}
    },
    dialogBeforeClose() {
      this.dialogVisible = false
    },
    handleOpen() {
      this.loading = true
      this.dialogVisible = true
      basicData.bizQualificationCategoryQuery(this.queryParam).then((res) => {
        this.loading = false
        this.aptitudeList = res.value.rows
      })
    },
    openExpert() {
      this.$refs.troubleshooting.add()
    },
    openCompany() {
      this.$refs.unit.add()
    },
    companyList(data) {
      console.log(data)
    },
    // 保存
    handleSave() {
      this.parameter.accessoryList = []
      this.parameter.accessoryList = this.dataList
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          this.saveing = true
          basicData
            .bizQualificationLabelSaveOrUpdate(this.parameter)
            .then((res) => {
              this.saveing = false
              if (res.state) {
                this.$message.success('保存成功')
                if (this.breadcrumbOpt[1].breadcrumbName === '编辑') {
                  this.$router.push({
                    name: 'qualificationManagement',
                    params: {
                      tabsActiveName: 'libraryQualifications',
                      pageBean: this.$route.query.pageBean,
                    },
                  })
                } else {
                  this.$router.push({
                    name: 'qualificationManagement',
                    params: {
                      tabsActiveName: 'libraryQualifications',
                    },
                  })
                }
              }
            })
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
// /deep/.el-row {
//   padding: 0 100px;
// }
.rows {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ebebeb;
  margin-bottom: 16px;
  padding: 10px 0;
  .rows-left {
    margin-right: 10px;
    .rows-hr {
      width: 3px;
      height: 18px;
      background-color: #0e6eff;
      border-radius: 2px;
    }
  }
  .rows-title {
    .text-overflow {
      width: 100%;
      font-size: 16px;
    }
  }
}
</style>
