<template>
  <div>
    <!-- <el-button type="primary" size="small" @click="addBtn">添 加</el-button> -->
    <el-button type="primary" size="small" :disabled="disabled" @click="addBtn">添 加</el-button>
    <el-dialog title="报价单列表" append-to-body width="50%" :show-close="false" :visible.sync="drawer2">
      <div class="inline-16" style="margin-bottom:10px">
        <el-input suffix-icon="el-icon-search" size="small" v-model="params2.content.where.condition" placeholder="产品名称,编号" @keyup.enter.native="getQuotationList(params2.content.pageNumber=1)" @clear="getQuotationList(params2.content.pageNumber = 1)" clearable></el-input> 
      </div>
      <el-table
        :data="ENlist"
        stripe
        style="width: 100%"
        height="300"
        border>
        <el-table-column
            prop="status"
            label="状态"
            width="180">
        </el-table-column>
        <el-table-column
          prop="billno"
          label="单号"
          width="180">
        </el-table-column>
        <el-table-column
          prop="submitby"
          label="提交人"
          width="180">
        </el-table-column>
        <el-table-column
          prop="submitdate"
          label="提交时间">
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="rowClick(scope.row)">选 择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="display:flex;justify-content:space-between;margin-top:16px;">
        <div style="text-align:left">
        <el-pagination
            background
            small
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
            :current-page="params2.content.pageNumber"
            :page-size="params2.content.pageSize"
            layout="total, prev, pager, next"
            :total="total2">
          </el-pagination>
        </div>
        <el-button size="mini" @click="cancel()">取消</el-button>
      </div>
    </el-dialog>
    <el-drawer append-to-body size="80%" :with-header="false"  :show-close="false" :visible.sync="drawer">

      <div class="container">
        <p class="normal-title normal-margin">产品清单</p>
         <div style="display:flex;align-items:center;margin-bottom:10px">
           <span class="header-title">选择报价单:</span>
            <el-input readonly type="text" placeholder="选择报价单" style="width:200px" size="small" @focus="drawer2=true;getQuotationList()" v-model="currentQuotation.billno"></el-input>
          </div>
        <el-divider></el-divider>
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">
          <div style="display:flex;align-items:center">
            <el-input size="small" style="width:200px" v-model="params.content.where.condition" placeholder="输入搜索内容" @clear="getProductList(params.content.pageNumber = 1)" @keyup.native.enter="getProductList(params.content.pageNumber = 1)" clearable></el-input>
          </div>
          <div>
            <el-button type="primary" size="small" :disabled="selectProductLength == 0" @click="queryProuctAdds($refs.table.tableSelectData)">批 量 添 加</el-button>
          </div>
        </div>
        <Table  ref="table" fixedName="operation" v-model="itemno"  :data="productList" :custom="true" height="500px"   @selection="selectArr" @onSelect="queryProuctAdd">
        </Table>
        <div style="display:flex;justify-content:space-between;align-items:center;margin-top:10px">
          <span>已添加产品数:{{addProductLength}}</span>
          <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="params.content.pageNumber"
              :page-sizes="[20, 50, 100, 200]"
              :page-size="100"
              layout="total,sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
// import Table from '@/HDrpManagement/ProductGroupMag/modules/table'
import Table from '@/components/productTable/indexQty'
import previewImage from '@/components/previewImage/index'
import { log } from '@antv/g2plot/lib/utils';
export default {
  props:['disabled','data'],
  name: '',
  components:{Table,previewImage},
  data() {
    return {
      drawer:false,
      drawer2:false,
      form:{
        qty:'',
        discountrate:'',
        price:'',
      },
      currentQuotation:{},
      selectProductLength:0,
      addProductLength:0,
      tablecols:[],
      productList:[],
      itemno:'',
      total:0,
      total2:0,
      timer:0,
      ENlist:[],
      params: {
        "id": 20221123162902,
        "content": {
            "sa_contractid": '',
            "pageNumber": 1,
            "pageSize": 100,
            "nocache":true,
            "where": {
                "condition": ""
            }
        },
      },
      // params2: {
      //   "id": 20221123162902,
      //   "content": {
      //       "sa_contractid": '',
      //       "pageNumber": 1,
      //       "pageSize": 20,
      //       "nocache":true,
      //       "where": {
      //           "condition": ""
      //       }
      //   },
      // }
      params2: {
        "id": 20221222151302,
        "content": {
            "sa_projectid": '',
            "pageNumber": 1,
            "pageSize": 20,
            "where": {
                "condition": ""
            }
        },
      }
    };
  },
  computed:{
  },
  watch:{
    drawer (val) {
      if (!val) {
        this.$refs.table.allArr = []
        this.currentQuotation = {}
        this.productList = []
        console.log(this.$refs.table.allArr);
        
      }
    }
  },
  updated () {
    setTimeout(() => {
      this.addProductLength = this.$parent.list.length
    },300)
  },
  created () {
    this.tablecols = this.tool.tabelCol(this.$route.name)['productTable'].tablecols
  },
  methods: {
    cancel () {
      this.drawer2=false
    },
    rowClick (data) {
      console.log(data);
      this.drawer2 = false
      this.currentQuotation = data
      this.getProductList(data)
    },
    addBtn () {
      console.log("执行")
      this.drawer = true
      this.getQuotationList()
    },
    debounce (fn, wait) {
      let that = this
      return function () {
        if (that.timer !== null) clearTimeout(that.timer)
        that.timer = setTimeout(fn, wait)
      }
    },
    async getProductList (data) {
      this.params.content.sa_contractid = this.$route.query.id
      this.params.content.sa_quotedpriceid = this.currentQuotation.sa_quotedpriceid

      let res = await this.$api.requested(this.params)
      this.productList = res.data
      this.total = res.total
      console.log(this.productList);
      
    },
    selectArr (data) {
      this.selectProductLength = data.length
    },
    batchSelect(data){
      this.debounce(() => {
        this.addProduct(data)
      },300)()
    },
    async addProduct (data) {
      console.log(data,'data1111')
      let res = await this.$api.requested({
        "id": 20221123164402,
        "content": {
            "sa_contractid": this.$route.query.id,
            "items": [
              {
                "itemid": data.itemid,
                "price": data.price,
                "qty": data.qty,
                "marketprice":data.marketprice,
                "discountrate":data.discountrate,
                "type":'指定单价'
              }
            ]
        },
      })
      this.tool.showMessage(res,() => {
        this.getProductList()
        this.$emit('onSuccess')
      })
    },
    batchSelects(data){
      this.debounce(() => {
        this.onSumit(data)
      },300)()
    },
    async onSumit (data) {
      console.log(this.$refs.table.tableSelectData);
      let res = await this.$api.requested({
        "id": 20221123164402,
        "content": {
            "sa_contractid": this.$route.query.id,
            "items": data
        },
      })
      this.tool.showMessage(res,() => {
        this.$emit('onSuccess')
        this.$refs.table.tableSelectData = []
        this.productList = []
      })
    },
    /*查询商品是否已添加*/
    async queryProuctAdds(data){
      let item = data.map(item => {
        return {
          "itemid": item.itemid,
          "price": item.price,
          "qty": item.qty,
          "marketprice":item.marketprice,
          "discountrate":item.discountrate,
          "type":'指定单价'
        }
      })
      console.log(item,'批量添加')
      let checkItem = []
      item.forEach((item,index)=>{
        checkItem[index] = item.itemid
      })
      console.log(checkItem,'校验id')
      const res = await this.$api.requested({
        "id": 20230221151903,
        "content": {
          "sa_contractid": this.$route.query.id,
          "itemids":checkItem
        },
      })
      console.log(res,'是否重复')
      if (!res.data){
        this.batchSelects(item)
      }else {
        this.checkItems(item)
      }
    },
    async queryProuctAdd(data){
      const res = await this.$api.requested({
        "id": 20230221151903,
        "content": {
          "sa_contractid": this.$route.query.id,
          "itemids":[data.itemid]
        },
      })
      console.log(res,'是否重复')
      if (!res.data){
        console.log(data,'不重复的数据')
        this.batchSelect(data)
      }else {
        this.checkItem(data)
      }

    },
    checkItem(data) {
      this.$confirm('商品已存在, 是否更新最新价格?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal:false,
        type: 'warning'
      }).then(() => {
        this.batchSelect(data)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消添加'
        });
      });
    },
    checkItems(data) {
      this.$confirm('商品已存在, 是否更新最新价格?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal:false,
        type: 'warning'
      }).then(() => {
        this.batchSelects(data)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消添加'
        });
      });
    },
    upDateData (data) {
      this.selectProductLength = data.length
    },
    async getQuotationList () {
      this.params2.content.sa_projectid = this.data.sa_projectid
      let res = await this.$api.requested(this.params2)
      this.ENlist = res.data
      this.total2 = res.total
      
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params.content.pageSize = val
      this.getProductList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.params.content.pageNumber = val
      this.getProductList()
    },
    handleSizeChange2(val) {
      // console.log(`每页 ${val} 条`);
      this.params2.content.pageSize = val
      this.getQuotationList()

    },
    handleCurrentChange2(val) {
      // console.log(`当前页: ${val}`);
      this.params2.content.pageNumber = val
      this.getQuotationList()
    },
  },
};
</script>

<style scoped>
.el-divider {
  margin: 16px 0 !important;
}
.header-title {
  font-size:14px;
  margin-right:10px;
  position: relative;
  margin-left: 10px;
}
.header-title::before {
  display: inline-block;
  content: '*';
  color: red;
  position: absolute;
  left: -10px;
}
</style>
