<template>
  <div class="pageBox">
    <div class="searchBox">
      <div class="row">
        <span class="span">供应商名称：</span>
        <div class="right"><el-input v-model="supplier_name" class="wid100" clearable></el-input></div>
      </div>
      <div class="row">
        <el-button type="primary" @click="handleSearch"><el-icon><Search /></el-icon>&nbsp;筛选</el-button>
      </div>
    </div>

    <el-card shadow="never">
      <div class="opaBox">
        <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>&nbsp;新增</el-button>
        <!-- <el-button type="warning" @click="handleExport"><span class="iconfont icon-daochu"></span>&nbsp;导出</el-button> -->
      </div>
      <el-table :data="goodsList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="supplier_name" label="供应商名称" />
        <el-table-column label="营业执照" align="center">
          <template #default="scope">
            <div class="imgBox" v-if="scope.row.business_license_path">
              <el-image :z-index="9999" :src="scope.row.business_license_path" :hide-on-click-modal="true" :preview-src-list="[scope.row.business_license_path]" fit="cover" :preview-teleported="true" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="生产许可证" align="center">
          <template #default="scope">
            <div class="imgBox" v-if="scope.row.production_license_path">
              <el-image :z-index="9999" :src="scope.row.production_license_path" :hide-on-click-modal="true" :preview-src-list="[scope.row.production_license_path]" fit="cover" :preview-teleported="true" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="合同">
          <template #default="scope">
            <div v-if="scope.row.contract_path">
              <div v-for="(it, i) in scope.row.contract_path" :key="i">
                <a :href="it" target="_blank">合同附件</a>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="bank_account" label="银行帐户" />
        <el-table-column prop="bank_account_holder" label="银行开户名" />
        <el-table-column prop="bank_branch_name" label="开户银行支行名称" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button type="primary" circle @click="handleEdit(scope.row)"><el-icon><Edit /></el-icon></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-pagination">
        <el-pagination
          :current-page="page"
          background
          layout="prev, pager, next, sizes, total"
          :total="total"
          :page-sizes="[10, 50, 100]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"></el-pagination>
      </div>
    </el-card>

    <el-dialog v-model="showDialog" width="900px" :title="opaType == 'add' ? '新增' : '编辑' ">
      <el-form label-position="right" label-width="150px">
        <el-form-item label="供应商名称：">
          <el-input v-model="itemInfo.supplier_name" clearable></el-input>
        </el-form-item>
        <el-form-item label="营业执照：">
          <el-upload
            ref="yyzzRef"
            action="/api/upload/img"
            :headers="headers"
            :on-remove="handleRemoveYyzzImg"
            :on-error="handleUploadError"
            :on-preview="handlePreview"
            :on-success="handleYyzzSuccess"
            :file-list="yyzzList"
            :show-file-list="true"
            list-type="picture-card"
            accept=".png,.jpg,.gif">
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="生产许可证：">
          <el-upload
            ref="xkzRef"
            action="/api/upload/img"
            :headers="headers"
            :on-remove="handleRemoveXkzImg"
            :on-error="handleUploadError"
            :on-preview="handlePreview"
            :on-success="handleXkzSuccess"
            :file-list="xkzList"
            :show-file-list="true"
            list-type="picture-card"
            accept=".png,.jpg,.gif">
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="合同：">
          <el-upload
            ref="fileRef"
            action="/api/upload/file"
            :on-success="handleFileSuccess"
            :on-remove="handleFileRemove"
            :before-upload="handleBeforeUpload"
            :on-error="handleUploadError"
            :on-preview="previewFile"
            :headers="headers"
            multiple
            :file-list="fileList"
            :show-file-list="true">
            <el-button type="primary">上传附件</el-button>
            <template #tip>
              <div class="el-upload__tip">请上传zip、pdf、excel、doc（docx）格式附件，最大限制为 4 M</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="银行帐户：">
          <el-input v-model="itemInfo.bank_account" clearable placeholder="请输入银行账户"></el-input>
          <div style="color: #f00;font-size: 12px;">请仔细核对银行账户</div>
        </el-form-item>
        <el-form-item label="银行开户名：">
          <el-input v-model="itemInfo.bank_account_holder" clearable placeholder="请输入银行开户名"></el-input>
        </el-form-item>
        <el-form-item label="开户银行支行名称：">
          <el-input v-model="itemInfo.bank_branch_name" clearable placeholder="请输入银行开户名"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="commitSupplier()" :loading="opa_loading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预览图片 -->
    <el-dialog v-model="picVisible" center width="800px">
      <img :src="dialogImageUrl" style="max-width: 700px; margin: 0 auto;display: block;" />
    </el-dialog>

  </div>
</template>

<script>
import { onMounted, reactive, toRefs, ref, nextTick } from "vue"
import { get, post } from "@/api/request"
import { Search, Plus, Edit, ZoomIn, Delete } from '@element-plus/icons'
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseErrors } from 'components/common'

export default {
  components: {
    Search, Plus, Edit, ZoomIn, Delete
  },
  setup() {
    const data = reactive({
      headers: {
        Authorization: localStorage.getItem('token'),
        'Shop-Id': localStorage.getItem('shopId') || ''
      },
      supplier_name: '',
      goodsList: [],
      page: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      opaType: '',
      showDialog: false,
      opa_loading: false,
      Type: {
        'default': '默认'
      },
      itemInfo: {},
      picVisible: false,
      dialogImageUrl: '',
      fileList: [],
      yyzzList: [],
      xkzList: [],

    })

    function handleSearch() {
      data.page = 1
      fetchData()
    }

    const fetchData = () => {
      data.loading = true
      let params = {
        page: data.page,
        pageSize: data.pageSize,
        supplier_name: data.supplier_name
      }
      get(`/api/purchaseSupplier`, params).then((res) => {
        data.goodsList = res.data
        data.total = res.meta.total
        data.loading = false
      }).catch(() => {
        data.loading = false
      })
    }

    function handleCurrentChange(e) {
      data.page = e
      fetchData()
    }

    function handleSizeChange(e) {
      data.page = 1
      data.pageSize = e
      fetchData()
    }

    function handleAdd() {
      data.opaType = 'add'
      data.itemInfo = {
        type: 'default',
        sort: 0,
        status: 1
      }
      data.showDialog = true
    }

    function handleEdit(item) {
      data.opaType = 'edit'
      data.itemInfo = JSON.parse(JSON.stringify(item))
      data.yyzzList = item.business_license_path ? [{url: item.business_license_path}] : []
      data.xkzList = item.production_license_path ? [{url: item.production_license_path}] : []
      data.fileList = []
      if(item.contract_path && item.contract_path.length) {
        item.contract_path.forEach(it => {
          data.fileList.push({name: '合同附件', url: it})
        })
      }
      data.showDialog = true
    }
    
    function commitSupplier() {
      if(!data.itemInfo.supplier_name) {
        return ElMessage.info('请输入供应商名称')
      } else if(!data.yyzzList.length) {
        return ElMessage.info('请上传营业执照')
      } else if(!data.fileList.length) {
        return ElMessage.info('请上传合同附件')
      } else if(!data.itemInfo.bank_account) {
        return ElMessage.info('请输入银行账户')
      } else if(!data.itemInfo.bank_account_holder) {
        return ElMessage.info('请输入银行开户名')
      } else if(!data.itemInfo.bank_branch_name) {
        return ElMessage.info('请输入银行开户名')
      }
      data.opa_loading = true
      let imgs = []
      for (let index = 0; index < data.fileList.length; index++) {
        const obj = data.fileList[index]
        imgs.push(obj.url)
      }
      let params = {
        supplier_name: data.itemInfo.supplier_name,
        business_license_path: data.yyzzList[0].url,
        production_license_path: data.xkzList[0] && data.xkzList[0].url || '',
        contract_path: imgs,
        bank_account: data.itemInfo.bank_account,
        bank_account_holder: data.itemInfo.bank_account_holder,
        bank_branch_name: data.itemInfo.bank_branch_name
      }

      if(data.opaType == 'add') {
        post(`/api/purchaseSupplier`, params).then(() => {
          clearForm()
          data.page = 1
          fetchData()
          ElMessage({ type: 'success', message: '新增成功' })
          data.showDialog = false
          data.opa_loading = false
        }).catch((err) => {
          data.opa_loading = false
          parseErrors(err.response.data.errors)
        })
      } else {
        post(`/api/purchaseSupplier/${data.itemInfo.id}`, params, 'PUT').then(() => {
          clearForm()
          fetchData()
          ElMessage({ type: 'success', message: '编辑成功' })
          data.showDialog = false
          data.opa_loading = false
        }).catch((err) => {
          data.opa_loading = false
          parseErrors(err.response.data.errors)
        })
      }
    }

    function handleRemoveYyzzImg(res, ress) {
      data.yyzzList = []
    }

    function handleRemoveXkzImg(res, ress) {
      data.xkzList = []
    }

    function handleUploadError(err) {
      if(JSON.parse(err.message) && JSON.parse(err.message).message) {
        ElMessage({ type: 'error', message: JSON.parse(err.message).message })
      }
    }

    function handleYyzzSuccess(res) {
      data.yyzzList = [{url: res.data.link}]
    }

    function handleXkzSuccess(res) {
      data.xkzList = [{url: res.data.link}]
    }

    function handlePreview(File) {
      data.dialogImageUrl = File.url
      data.picVisible = true
    }

    function handleFileSuccess(res, ress) {
      data.fileList.push({ url: res.data.link })
    }
    function handleFileRemove(res, ress) {
      data.fileList = ress
    }

    function previewFile(File) {
      window.open(File.url || File.response.data.link)
    }
    
    const handleBeforeUpload = (file) => {
      let type = file.name.indexOf('.pdf') !== -1 || file.name.indexOf('.doc') !== -1 || file.name.indexOf('.docx') !== -1 || file.name.indexOf('.zip') !== -1 || file.name.indexOf('.xlsx') !== -1
      if (type) {
        const isLt4M = file.size / 1024 / 1024 < 4
        if (!isLt4M) {
          ElMessage.error('附件上传大小不能超过 4MB!')
          return false
        }
      } else {
        ElMessage.error('上传文件格式不正确')
        return false
      }
    }

    const yyzzRef = ref(null)
    const xkzRef = ref(null)
    const fileRef = ref(null)

    function clearForm() {
      data.yyzzList = []
      data.xkzList = []
      data.fileList = []
      nextTick(() => {
        yyzzRef.value.clearFiles()
        xkzRef.value.clearFiles()
        fileRef.value.clearFiles()
      })
    }

    onMounted(() => {
      fetchData()
    })

    return {
      yyzzRef,
      xkzRef,
      fileRef,
      parseErrors,
      ...toRefs(data),
      handleSearch,
      handleCurrentChange,
      handleSizeChange,
      fetchData,
      handleAdd,
      handleEdit,
      commitSupplier,
      handleRemoveYyzzImg,
      handleRemoveXkzImg,
      handleUploadError,
      handlePreview,
      handleYyzzSuccess,
      handleXkzSuccess,
      handleFileSuccess,
      handleFileRemove,
      previewFile,
      handleBeforeUpload,
      clearForm
    }
  }
}
</script>

<style lang="scss" scoped>
  .searchBox{
    display: flex;
    flex-wrap: wrap;
    background-color: #fff;
    padding: 15px 0 0 0;
    border-radius: 4px;
    margin-bottom: 15px;
    .row{
      display: flex;
      align-items: center;
      width: 20%;
      box-sizing: border-box;
      margin-bottom: 15px;
      &.row1{
        width: 25%;
      }
      .span{
        display: block;
        width: 100px;
        font-size: 14px;
        text-align: right;
        box-sizing: border-box;
      }
      .right{
        width: calc(100% - 120px);
      }
      .wid100{
        width: 100%;
      }
    }
  }
  .opaBox{
    margin-bottom: 15px;
  }
  .imgBox{
    display: flex;
    flex-wrap: wrap;
    .el-image{
      width: 60px;
      height: 60px;
      border-radius: 4px;
      margin-right: 10px;
    }
  }
  .skuBox{
    border: 1px solid #e5e5e5;
    border-radius: 5px;
    padding: 15px 0;
    margin-bottom: 15px;
    background-color: #f3f3f3;
    .tit{
      padding-left: 40px;
      font-weight: 600;
      font-size: 15px;
      margin-bottom: 15px;
    }
  }
</style>
