<template>
  <div class="customer-css" >
    <!--  查询时间和产品  -->
    <el-form :inline="true" label-position="top" label-width="100px" style="margin-top: 0px;" >
      <el-row>
        <el-col :span="24" style="">
          <el-form-item :label="'请求日期'" >
            <el-date-picker
              style="width: 130px"
              v-model="searchData.startDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="开始">
            </el-date-picker>
          </el-form-item>
          <el-form-item :label="'至'" >
            <el-date-picker
              style="width: 130px"
              v-model="searchData.endDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="结束">
            </el-date-picker>
          </el-form-item>
<!--          <el-form-item :label="'Status:'">-->
<!--            <el-select v-model="searchData.status"  style="width: 130px">-->
<!--              <el-option label="All" value=""></el-option>-->
<!--              <el-option label="待审批" value="待审批"></el-option>-->
<!--              <el-option label="审批通过" value="审批通过"></el-option>-->
<!--              <el-option label="已拒绝" value="已拒绝"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item >
            <span style="cursor: pointer" slot="label" @click="getBaseList(501,1)"><a href="#">供应商编码</a></span>
            <el-input v-model="searchData.supplierNo" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="'供应商名称:'">
            <el-input v-model="searchData.supplierName" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="'请求人:'">
            <el-input v-model="searchData.requestBy" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="'请求编号:'">
            <el-input v-model="searchData.requestNo" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="' '" >
            <el-button class="customer-bun-min" type="primary" @click="getMainData" style="">查询</el-button>
<!--            <el-button class="customer-bun-min" type="primary" @click="requestModel" style="">New Request</el-button>-->
            <el-button @click="exportExcel()" type="primary" style="margin-left: 2px">{{'导出'}}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table
      :height="height"
      :data="mainDataList"
      border
      ref="mainTable"
      highlight-current-row
      v-loading="dataListLoading"
      style="margin-top: 0px; width: 100%;">
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="220"
        :label="'操作'">
        <template slot-scope="scope">
          <a type="text" size="small" @click="requestModel(scope.row)">审批</a>

        </template>
      </el-table-column>
      <el-table-column
        v-for="(item,index) in columnList1" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed==''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="!item.columnHidden"> {{scope.row[item.columnProp]}}</span>
          <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]"
                                             style="width: 100px; height: 80px"/></span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页插件 -->
    <el-pagination style="margin-top: 0px"
                   @size-change="sizeChangeHandle"
                   @current-change="currentChangeHandle"
                   :current-page="pageIndex"
                   :page-sizes="[20, 50, 100, 200, 500]"
                   :page-size="pageSize"
                   :total="totalPage"
                   layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <el-dialog title="审批申请" :close-on-click-modal="false" v-drag :visible.sync="requestModelFlag" width="600px">
      <el-form  label-position="top"  style="margin-top: -5px;">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item  label="供应商编码">
              <el-input v-model="requestModelData.supplierNo" disabled style="width: 130px" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="'供应商名称'" >
              <el-input v-model="requestModelData.supplierName" disabled style="width: 130px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="'请求日期'" >
              <el-date-picker
                style="width: 130px"
                v-model="requestModelData.requestDate"
                type="date"
                disabled
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="'新供应商等级'" >
              <el-select v-model="requestModelData.newSupplierGroup" disabled style="width: 130px">
                <el-option label="战略" value="战略"></el-option>
                <el-option label="重要" value="重要"></el-option>
                <el-option label="普通" value="普通"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="'原因'" >
              <el-input v-model="requestModelData.reason" disabled ></el-input>
            </el-form-item>
          </el-col>
<!--          <el-col :span="4">-->
<!--            <el-button class="customer-bun-min" type="primary" @click="handleUpload" style="">Upload</el-button>-->
<!--          </el-col>-->
        </el-row>

      </el-form>

      <el-table
                :height="240"
                :data="fileList"
                ref="fileTableRef"
                style="width: 100%;" >
        <el-table-column
          prop="fileName"
          header-align="center"
          align="left"
          min-width="200"
          label="文件名">
        </el-table-column>
        <el-table-column
          prop="createdBy"
          header-align="center"
          align="center"
          min-width="100"
          label="上传人">
        </el-table-column>
        <el-table-column
          prop="createDate"
          header-align="center"
          align="center"
          min-width="100"
          label="上传时间">
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          width="100"
          fixed="right"
          label="操作">
          <template slot-scope="scope">
            <a type="text" size="small"  @click="handleDownload(scope.row)">查看 </a>
<!--            <a type="text" size="small" @click="deleteFile(scope.$index)">| delete</a>-->
          </template>
        </el-table-column>
      </el-table>
      <el-radio v-model="radio" label="审批通过">审批</el-radio>
      <el-radio v-model="radio" label="已拒绝">拒绝</el-radio>
      <el-footer style="height:40px;margin-top: -20px;text-align:center">
        <el-button type="primary" @click="submitData()">提交</el-button>
        <el-button type="primary" @click="requestModelFlag=false">取消并关闭</el-button>
      </el-footer>
    </el-dialog>

    <el-dialog title="上传" :visible.sync="ossVisible" v-drag width="400px" append-to-body :close-on-click-modal="false">
      <el-form ref="form"  class="rq" label-width="80px" label-position="top">
        <el-row :gutter="10">
          <slot></slot>
          <el-col :span="24">
            <el-form-item label=" " class="auto">
              <el-upload drag :file-list="fileList2"
                         action="#" ref="upload"
                         :on-remove="onRemoveFile"
                         :on-change="onChangeFile"
                         multiple
                         :auto-upload="false">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" class="auto">
              <el-input type="textarea" v-model="ossForm.remark" resize="none" :autosize="{minRows: 3, maxRows: 3}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="uploadLoading" @click="handleUploadFiles">确认</el-button>
      <el-button @click="ossVisible = false">取消</el-button>
    </span>
    </el-dialog>


    <Chooselist ref="baseList" @getBaseData="getBaseData"></Chooselist>
  </div>
</template>

<script>
/*组件*/
import excel from "@/utils/excel-util.js";
import {
  confirmRequest,getSupplierGroupRequestList,checkSrmSupplierList
} from '@/api/srm/srmSupplier.js'

import Chooselist from '@/views/modules/common/Chooselist_eam'
import {ossUploadNoSaveOSS, previewOssFileById, queryOss} from "../../../api/oss/oss";
export default {
  data() {
    return {
      functionId: this.$route.meta.menuId,
      height: 200,
      currentRow: {},
      searchData:{
        startDate:'',
        endDate:'',
        status:'待审批',
        supplierNo:'',
        supplierName:'',
        requestBy:'',
        requestNo:'',
        site:this.$store.state.user.site,
        page: 1,
        limit: 10,
      },
      uploadLoading:false,
      exportName: '供应商等级变更申请'+this.dayjs().format('YYYYMMDDHHmmss'),
      tagNo:'',
      tagType:'',
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      mainDataList:[],
      dataListLoading: false,
      requestModelFlag: false,
      requestModelData:{
        id:'',
        site:'',
        requestNo:'',
        supplierNo:'',
        supplierName:'',
        requestDate:'',
        createBy:'',
        oldSupplierGroup:'',
        newSupplierGroup:'',
        reason:'',
        status:'',
        fileList:[],
      },
      fileList:[],
      fileList2:[],
      ossVisible:false,
      ossForm:{
        remark:'',
      },
      radio:'审批通过',
      columnList1: [
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '811011Table1RequestNo',
          tableId: "811011Table1",
          tableName: "供应商等级变更申请",
          columnProp: "requestNo",
          headerAlign: "center",
          align: "left",
          columnLabel: "请求编号",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '811011Table1RequestDate',
          tableId: "811011Table1",
          tableName: "供应商等级变更申请",
          columnProp: "requestDate",
          headerAlign: "center",
          align: "left",
          columnLabel: "请求日期",
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '811011Table1SupplierNo',
          tableId: "811011Table1",
          tableName: "供应商等级变更申请",
          columnProp: "supplierNo",
          headerAlign: "center",
          align: "left",
          columnLabel: "供应商编码",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '811011Table1SupplierName',
          tableId: "811011Table1",
          tableName: "供应商等级变更申请",
          columnProp: "supplierName",
          headerAlign: "center",
          align: "left",
          columnLabel: "供应商名称",
          columnWidth: '240',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '811011Table1OldSupplierGroup',
          tableId: "811011Table1",
          tableName: "供应商等级变更申请",
          columnProp: "oldSupplierGroup",
          headerAlign: "center",
          align: "left",
          columnLabel: "旧供应商等级",
          columnWidth: '140',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '811011Table1NewSupplierGroup',
          tableId: "811011Table1",
          tableName: "供应商等级变更申请",
          columnProp: "newSupplierGroup",
          headerAlign: "center",
          align: "left",
          columnLabel: "新供应商等级",
          columnWidth: '140',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '811011Table1Reason',
          tableId: "811011Table1",
          tableName: "供应商等级变更申请",
          columnProp: "reason",
          headerAlign: "center",
          align: "left",
          columnLabel: "原因",
          columnWidth: '200',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '811011Table1Status',
          tableId: "811011Table1",
          tableName: "供应商等级变更申请",
          columnProp: "status",
          headerAlign: "center",
          align: "center",
          columnLabel: "状态",
          columnWidth: '80',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: '811011Table1RequestBy',
          tableId: "811011Table1",
          tableName: "供应商等级变更申请",
          columnProp: "requestBy",
          headerAlign: "center",
          align: "left",
          columnLabel: "请求人",
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
      ],
    }
  },
  /*组件*/
  components: {
    Chooselist,

  },
  watch: {
    requestModelData: {
      deep: true,
      handler: function (newV, oldV) {
        this.requestModelData.supplierNo = this.requestModelData.supplierNo.toUpperCase()
      }
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.height = window.innerHeight - 220;
    })
  },
  methods: {
    // 获取基础数据列表S
    getBaseList(val, type) {
      this.tagNo = val
      this.tagType = type
      this.$nextTick(() => {
        let strVal = ''
        let conSql = ''
        if (val === 501) {
          if(type==1){
            strVal = this.searchData.supplierNo || ''
          }
          if(type==2){
            strVal = this.requestModelData.supplierNo || ''
          }
          conSql = " and site = '" + this.$store.state.user.site + "'"
        }
        this.$refs.baseList.init(val, strVal, conSql)
      })
    },

    /* 列表方法的回调 */
    getBaseData(val) {
      console.log('Chooselist返回的数据:', val, 'tagNo:', this.tagNo, 'tagType:', this.tagType)
      if (this.tagNo === 501) {
        // 供应商编码字段 - SQL返回: SupplierID, SupplierName
        const supplierNoVal = val.SupplierID || val.supplierID || val.supplierId || ''
        const supplierNameVal = val.SupplierName || val.supplierName || val.supplier_name || ''
        
        if(this.tagType==1) {
          this.searchData.supplierNo = supplierNoVal
          console.log('查询条件-供应商编码赋值:', supplierNoVal)
        }
        if(this.tagType==2) {
          this.requestModelData.supplierNo = supplierNoVal
          this.requestModelData.supplierName = supplierNameVal
          this.requestModelData.oldSupplierGroup = val.supplier_group || ''
          console.log('弹窗-供应商编码赋值:', supplierNoVal, '供应商名称赋值:', supplierNameVal)
        }
      }
    },
    getMainData(){
      this.searchData.limit = this.pageSize
      this.searchData.page = this.pageIndex
      getSupplierGroupRequestList(this.searchData).then(({data}) => {
        if (data.code === 0) {
          this.mainDataList = data.page.list
          this.pageIndex = data.page.currPage
          this.pageSize = data.page.pageSize
          this.totalPage = data.page.totalCount
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getMainData()
    },

    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getMainData()
    },
    async exportExcel() {
      this.searchData.limit = -1
      this.searchData.page = 1
      excel.exportTable({
        url: "/srmSupplier/getSupplierGroupRequestList",
        columnMapping:  this.columnList1,//可以直接用table，不需要的列就剔除
        mergeSetting: [],//需要合并的列
        params: this.searchData,
        fileName: this.exportName+".xlsx",
        rowFetcher: res => res.data,
        columnFormatter: [],
        dropColumns: [],//需要剔除的列，例如dropColumns: ["netWeight"]，即剔除净重列
      });
    },
    requestModel(row){
      this.requestModelData={
        id:row.id,
        site:row.site,
        requestNo:row.requestNo,
        supplierNo:row.supplierNo,
        supplierName:row.supplierName,
        requestDate:row.requestDate,
        oldSupplierGroup:row.oldSupplierGroup,
        newSupplierGroup:row.newSupplierGroup,
        updateBy:this.$store.state.user.name,
        reason:row.reason,
        status:'',
        fileList:[],
      }
      this.radio='审批通过'
      let params={
        orderRef1:row.site,
        orderRef2:row.requestNo,
        orderReftype:'SrmSupplierRequest',
      }
      queryOss(params).then(({data})=>{
        if (data && data.code === 0){
          this.fileList = data.rows;
        }else {
          this.$message.warning(data.msg);
        }
        this.queryLoading = false;
      })
      this.requestModelFlag=true
    },
    // submitData(){
    //   if(this.requestModelData.supplierNo==''||this.requestModelData.supplierNo==null){
    //     this.$message.warning('未选择Supplier No！')
    //     return false
    //   }
    //   if(this.requestModelData.requestDate==''||this.requestModelData.requestDate==null){
    //     this.$message.warning('未选择Request Date！')
    //     return false
    //   }
    //   if(this.requestModelData.newSupplierGroup==''||this.requestModelData.newSupplierGroup==null){
    //     this.$message.warning('未选择Supplier Group！')
    //     return false
    //   }
    //   if(this.requestModelData.oldSupplierGroup===this.requestModelData.newSupplierGroup){
    //     this.$message.warning('新供应商等级与旧供应商等级相同！')
    //     return false
    //   }
    //   this.requestModelData.fileList= this.fileList
    //
    //   createNewSupplierRequest( this.requestModelData).then(({data})=>{
    //     if (data && data.code === 0){
    //       this.$message.success(data.msg);
    //       this.getMainData();
    //       this.requestModelFlag=false
    //     }else {
    //       this.$message.warning(data.msg);
    //     }
    //   }).catch((error)=>{
    //     this.$message.error(error);
    //   })
    //
    // },
    submitData(){

      this.$confirm(`确认审批此申请？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestModelData.status=this.radio
        confirmRequest(this.requestModelData).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success(data.msg);
            this.getMainData();
            this.requestModelFlag=false
          } else {
            this.$message.warning(data.msg);
          }
        })
      }).catch(() => {
      })
    },

    onRemoveFile(file, fileList){
      this.fileList2 = fileList
    },
    onChangeFile(file, fileList){
      this.fileList2 = fileList
    },
    handleUploadFiles(){
      if (this.fileList2.length === 0){
        this.$message.error('请选择文件');
        return;
      }
      let formData = new FormData();
      for (let i = 0; i < this.fileList2.length; i++) {
        formData.append('file', this.fileList2[i].raw);
      }
      formData.append('orderRef1', '');
      formData.append('orderRef2', '');
      formData.append('createdBy', this.$store.state.user.name);
      formData.append('fileRemark', this.ossForm.remark);
      this.uploadLoading = true;
      ossUploadNoSaveOSS(formData).then(({data})=>{
        if (data && data.code === 0){
          this.$message.success(data.msg);
          for (let i = 0; i <data.rows.length ; i++) {
            this.fileList.push(data.rows[i]);
          }
          this.ossVisible = false;
        }else {
          this.$message.warning(data.msg);
        }
        this.uploadLoading = false;
      }).catch((error)=>{
        this.$message.error(error);
        this.uploadLoading = false;
      })
    },
    handleUpload(){
      this.$nextTick(()=>{
        if (this.$refs.upload){
          this.$refs.upload.clearFiles();
        }
      })
      this.fileList2 = [];
      this.ossForm.remark = '';
      this.ossVisible = true
    },
    handleDownload(row){

      // 之前代码多选时只能下载一个，因为下载第一个后this.$refs.table.clearSelection()会清空选中项
      let selectList = [];
      selectList.push(row);
      for (let i = 0; i < selectList.length; i++) {
        let params = {
          id:selectList[i].id,
        }
        previewOssFileById(params).then((response) => {
          const blob = new Blob([response.data], { type: response.headers['content-type'] });
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.setAttribute('download', selectList[i].fileName);
          link.target = '_blank';  // 打开新窗口预览
          link.click();
          URL.revokeObjectURL(link.href);
        });
      }
    },
    deleteFile(index){
      this.fileList.splice(index, 1);
    },
    supplierNoBlur(){
      let params = {
        supplierNo: this.requestModelData.supplierNo,
        site: this.$store.state.user.site,
      }
      checkSrmSupplierList(params).then(({data}) => {
        if (data && data.code === 0) {
          if (data.rows.length >= 1){
            this.requestModelData.supplierName = data.rows[0].supplierName
          }else {
            this.requestModelData.supplierName = ''
          }
        }else {
          this.requestModelData.supplierName = ''
        }
      }).catch((error) => {
        this.$message.error(error)
      })
    },
  },
  created() {
    //查询报表的类型
    this.getMainData();
  },


}
</script>

<!--当前页面的标签样式-->
<style scoped lang="scss">

.rq .auto /deep/ .el-form-item__content{
  height: auto;
  line-height: 1.5;
}


</style>
