<template>
  <div>
    <el-button size="small" type="primary" @click="onShow" >添 加</el-button>
    <el-drawer
        title="添加产品配置单"
        :visible.sync="dialogFormVisible"
        size="80%"
        direction="rtl"
        :show-close="false"
        append-to-body
        @close="onClose">
      <div class="drawer__panel">
        <div class="flex-align-center flex-between " >
          <div class="flex-align-center" style="margin-top:-10px;margin-bottom: 10px;float: left">
            <el-input size="small"  suffix-icon="el-icon-search" v-model="params.content.where.condition" placeholder="产品名称,编号" @keyup.enter.native="listData(params.content.pageNumber = 1)" @clear="listData(params.content.pageNumber = 1)" clearable></el-input>&nbsp;
          </div>
          <div style="margin-top:-10px;margin-bottom: 10px;float: right">
            <div>
            <el-button style="float: right" type="primary" size="mini" @click="onSubmit(tableSelectData)" :disabled="tableSelectData.length === 0 ">批量添加</el-button>
            </div>
          </div>
        </div>
        <div class="container">
          <selectClass ref="classShow"  @brandChange="brandChange" @onClassChange="onClassChange" @Search="Search" @clearSearch="clearSearch" @clickStandard="clickStandard" @clickField="clickField" :default="true"></selectClass>
        </div>
        <div class="produtMag-panel">
          <el-table
              ref="multipleTable"
              height="calc(100vh - 370px)"
              :data="tableData"
              style="width: 100%"
              :header-cell-style="{height:'50px',color:'#606266',fontWeight:'400'}"
              :cell-style="{height:'50px',color:'#666666',fontWeight:'400'}"
              @selection-change="selectionChange">
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <el-table-column
                align="center"
                label="产品图"
                width="80">
              <template slot-scope="scope">
                <div v-if="scope.row.attinfos[0]">
                  <previewImage class="image" :image="scope.row.attinfos[0]" :list="scope.row.attinfos" :deletebtn="false"></previewImage>
                </div>
              </template>
            </el-table-column>
            <el-table-column
                prop="itemno"
                label="产品编号"
                width="180">
            </el-table-column>
            <el-table-column
                prop="itemname"
                label="产品名称"
                width="180">
            </el-table-column>
            <el-table-column
                prop="erpitemno"
                label="品号"
                width="180">
            </el-table-column>
            <el-table-column
                prop="standards"
                label="标准"
                width="100">
            </el-table-column>
            <el-table-column
                label="型号"
                width="180">
              <template slot-scope="scope">
                <p><span>{{scope.row.model || '--'}}</span></p>
              </template>
            </el-table-column>
            <el-table-column
                label="规格"
                width="180">
              <template slot-scope="scope">
                <p><span>{{scope.row.spec || '--'}}</span></p>
              </template>
            </el-table-column>
            <el-table-column
                prop="material"
                label="材质"
                width="180">
              <template slot-scope="scope">
                <p><span>{{scope.row.material || '--'}}</span></p>
              </template>
            </el-table-column>
            <el-table-column
                prop="device"
                label="装置"
                width="180">
              <template slot-scope="scope">
                <p><span>{{scope.row.device || '--'}}</span></p>
              </template>
            </el-table-column>
            <el-table-column
                prop="prodline"
                label="产线"
                width="180">
              <template slot-scope="scope">
                <p><span>{{scope.row.prodline || '--'}}</span></p>
              </template>
            </el-table-column>
            <el-table-column
                prop="specalnote"
                label="特殊说明"
                width="180">
              <template slot-scope="scope">
                <p><span>{{scope.row.specalnote || '--'}}</span></p>
              </template>
            </el-table-column>
            <el-table-column
                prop="brand"
                label="品牌"
                width="180">
              <template slot-scope="scope">
                <p v-for="(item,index) in scope.row.brand">
                  <span style="float: left" v-if="index === scope.row.brand.length -1">{{item?item.brandname+'':'--'}}</span>
                  <span style="float: left" v-else>{{item?item.brandname+',':'--'}}</span>
                </p>
              </template>
            </el-table-column>
            <el-table-column
                prop="itemclass"
                label="类别"
                width="180">
              <template slot-scope="scope">
                <p v-for="(item,index) in scope.row.itemclass">
                  <span style="float: left" v-if="index === scope.row.itemclass.length -1">{{item?item.itemclassname+'':'--'}}</span>
                  <span style="float: left" v-else>{{item?item.itemclassname+',':'--'}}</span>
                </p>
              </template>
            </el-table-column>
            <el-table-column
                prop="unitid"
                label="计量单位"
                width="100">
              <template slot-scope="scope">
                <el-tag size="mini" type="info" effect="plain">{{scope.row.unitname}}/{{scope.row.axunitname}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
                prop="marketprice"
                label="牌价(元)"
                fixed="right"
                width="80">
            </el-table-column>
            <el-table-column
                prop="num"
                fixed="right"
                label="数量"
                width="140">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.qty" size="mini" :min="1"  label="描述文字" @change="numChange(scope.row.qty,scope.$index,scope.row)"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column
                prop="price"
                label="单价"
                fixed="right"
                width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" size="mini" placeholder="请输入单价" @change="priceChange(scope.row.price,scope.$index,scope.row)"></el-input>
              </template>
            </el-table-column>
            <el-table-column
                prop="totalPrice"
                fixed="right"
                label="金额"
                width="100">
              <template slot-scope="scope">
                <span>{{tool.formatAmount(scope.row.totalPrice,2)}}</span>
              </template>
            </el-table-column>
            <el-table-column
                prop="totalPrice"
                fixed="right"
                label="操作"
                width="60">
              <template slot-scope="scope">
                <el-button type="text" @click="onSelect(scope.row)">添 加</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div>
            <div style="float: left">已选:{{selectTotal}}个商品</div>
            <div style="margin-top:16px;text-align:right">
              <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>

        </div>
      </div>
      <div class="fixed__btn__panel">
        <el-button size="small" @click="onClose" class="normal-btn-width">取 消</el-button>
<!--        <el-button size="small" type="primary" @click="onSubmit" :disabled="tableSelectData.length === 0 " class="normal-btn-width">确 定</el-button>-->
      </div>
    </el-drawer>
  </div>
</template>

<script>
import uploadFile from "@/components/upload/hw_obs_upload";
import previewImage from "@/components/previewImage";
import selectClass from './Select'
export default {
  name: "add",
  props:["discountrate"],
  components:{uploadFile, previewImage,selectClass},
  data(){
    return {
      dialogFormVisible:false,
      num:'',
      projectAddress:[],
      form:{
        "sa_projectid": "",
        "itemids": []
      },
      rules:{
        itemids:[
          { required: true, message: '请选择商品', trigger: 'blur'},
        ]
      },
      params:{
        "id": 20221021171802,
        "content": {
          "sa_projectid": 2,
          "pageNumber": 1,
          "pageSize": 100,
          "where": {
            "condition": "",
            "tradefield": "",
            "standards": "",
            "itemclassid": "",
            "sa_brandid": ""
          }
        },
      },
      tableSelectData:[],
      tableData: [],
      total:0,
      currentPage:0,
      selectTotal:0
    }
  },

  methods:{
    async onSubmit(data){
      const res = await this.$api.requested({
        "id": 20221021145502,
        "content": {
          "sa_projectid": this.$route.query.id,
          "items": data
        },
      })
     this.tool.showMessage(res,()=>{
       this.$emit('addSuccess')
       this.listData()
       this.selectData()
     })
      /*this.tableSelectData = []*/
      /*this.$refs['form'].validate(async (valid) => {
        if (!valid) return false
        this.form.sa_projectid = this.$route.query.id
        const res = await this.$api.requested({
          "id": "20221021145502",
          "version":1,
          "content": this.form
        })
        this.tool.showMessage(res,()=>{
          this.$emit('onSuccess')
          this.$refs['form'].resetFields();
          this.dialogFormVisible = false
        })
      })*/
    },
    onSelect(val){
      console.log(val,"选择的商品")
      this.tableSelectData = []
      this.tableSelectData[0] = val
      console.log(this.tableSelectData)
      this.onSubmit(this.tableSelectData)
    },
    onClose(){
      this.dialogFormVisible = false
      this.tableSelectData = []
      console.log("关闭设置产品")

    },
    onShow(){
      this.dialogFormVisible = true
      setTimeout(()=>{
        this.params.content.where.tradefield = this.$refs.classShow.field_act
       /* this.params.content.where.standards = this.$refs.classShow.standard_act*/
       /* this.params.content.where.itemclassid = this.$refs.classShow.class_act*/
        this.params.content.where.sa_brandid = this.$refs.classShow.brand_act
        this.listData()
        this.selectData()
      },1000)



     /* this.listData()
      this.selectData()*/
    },
    async listData () {
      console.log(this.params,"params")
      this.params.content.sa_projectid = this.$route.query.id
      const res = await this.$api.requested(this.params)
      console.log(res,'数据');
      
      this.tableData = res.data.map((item,index)=>{
        item.qty = 1
        item.price = Math.round((item.marketprice * (this.discountrate / 100) ) *100)/100
        item.totalPrice = item.qty * item.price
        return item
      })
      console.log(this.tableData,"报价表格数据")
      this.total = res.total
      this.currentPage = res.pageNumber
    },
    /*修改商品数量*/
    numChange(val,index,data){
      console.log(val,index,data)

      if (val < 0){
        data.qty = 1
      }else {
        data.qty = Math.round(val *100)/100
      }
      data.totalPrice = Math.round((data.qty * data.price) * 100) /100
      this.$set(this.tableData,index,data)
    /*  data.qty = val.toFixed(2)
      console.log(val,index)
      data.totalPrice = data.marketprice * data.qty
      console.log(data.marketprice,val,data.totalPrice)
      this.$set(this.tableData,index,data)  */
    },
    priceChange(val,index,data){
      console.log(val,index,data)
      if (val < 0){
        data.price = 0
      }else if (val > data.marketprice){
        data.price = data.marketprice
      }else {
        data.price = Math.round(val * 100)/100
      }
      data.totalPrice = Math.round((data.qty * data.price) * 100) /100
      this.$set(this.tableData,index,data)
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params.content.pageSize = val
      this.listData()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.params.content.pageNumber = val
      this.listData()
    },
    selectionChange (val) {
      this.tableSelectData = val
      this.$emit('selectionChange',val)
    },
    clearSelection () {
      this.$refs.multipleTable.clearSelection();
    },
    /*已选产品数据*/
    async selectData(){
      const res = await this.$api.requested({
        "id": 20221021145702,
        "content": {
          "sa_projectid": this.$route.query.id,
          "pageNumber": 1,
          "pageSize": 20,
          "where": {
            "condition": ""
          }
        },
      })
      this.selectTotal = res.total
      console.log(res.total,"已选产品数量")
    },
    brandChange(id) {
      this.brandId = id
      this.listData()
    },
    onClassChange (n) {
      this.params.content.where.itemclassid = n.itemclassid
      this.listData()
    },
    Search(data) {
      console.log(data,"搜索")
      this.params.content.where.condition = data
      this.params.content.pageNumber = 1
      this.listData()
    },
    clearSearch() {
      this.params.content.where.condition = ''
      this.params.content.pageNumber = 1
      this.listData()
    },
    clickField (item) {
      console.log(item,'clickField')
      this.params.content.where.tradefield = item.value
      this.listData()
    },
    clickStandard (item){
      this.params.content.where.standards = item.value
      this.listData()
    }
  },
  /*mounted() {
    this.listData()
  }*/
}
</script>

<style scoped>
/deep/.el-select {
  height: 28px !important;
  width: 100%;
}
/deep/.el-input__inner {
  height: 28px !important;
}
.produtMag-panel{
  /* margin: 30px; */
  padding:0 10px 10px 10px;
  background: #fff;
  border-radius:5px;
  overflow: hidden;
  border:1px solid rgb(0 0 0 / 5%)
  /* box-shadow: 0 5px 5px rgb(0 0 0 / 10%);
  transform: translate3d(0,-2px,0); */
}
.image {
  width:40px;height:40px;margin:0px auto;
}
</style>