<template>
  <div>
    <div style="margin-bottom: 15px">
      <el-input
          size="small"
          style="width: 200px;"
          class="inline-16"
          suffix-icon="el-icon-search"
          v-model="param.content.where.condition"
          placeholder="产品名称,产品编号,品号"
          @keyup.enter.native="productData(param.content.pageNumber = 1)"
          @clear="productData(param.content.pageNumber = 1)"
          clearable>
      </el-input>&nbsp;
<!--      <product_table style="float: right" :data="data"  ref="quoterPrice" @productAdd="productInitialization" ></product_table>-->
      <uploadAllData
          v-if="tool.checkAuth($route.name,'productDetails') && data.status === '新建' && disabled"
          class="inline-16"
          :total="total"
          @onSuccess="productData()"
          @handlePullApi="handlePullApi"
          @handleDelApi="handleDelApi"
          idName="sa_quotedprice_itemsid"
          type="del"
      ></uploadAllData>
      <el-button size="small" class="inline-16" :type="itemids.length === 0?'':'primary'" :disabled="itemids.length === 0" @click="deleteProducts">删除</el-button>
      <addProductProject v-if="tool.checkAuth($route.name,'productDetails') && data.status === '新建' && disabled && data.quotedpricetype === '项目报价'"
                           class="inline-16" @productAdd="productData" title="自项目产品添加" :params="paramsProjectAdd" :tablecolsAdd="tablecolsAdd"
                         @addSuccess="addProducts" @addProduct="addProduct" @uploadData="uploadData" @closeDrawer="productData"
                         :tradefield="data.tradefield" ref="addProductProject"
      ></addProductProject>
<!--      <productTable v-if="tool.checkAuth($route.name,'productDetails') && data.status === '新建' && disabled"  class="inline-16" @productAdd="productData"></productTable>-->
      <addProduct v-if="tool.checkAuth($route.name,'productDetails') && data.status === '新建' && disabled"
                  class="inline-16" @productAdd="productData" :params="paramsAdd" :tablecolsAdd="tablecolsAdd" title="自产品档案添加"
                  @addSuccess="addProducts" @addProduct="addProduct" @uploadData="uploadData" @closeDrawer="productData"
                  :tradefield="data.tradefield" ref="addProduct"
      ></addProduct>
    </div>
    <div class="produtMag-panel">
      <el-table
          ref="multipleTable"
          :data="list"
          style="width: 100%"
          height="calc(100vh - 500px)"
          :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"
            fixed>
        </el-table-column>
        <el-table-column
            align="center"
            label="产品图"
            width="100">
          <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="num"
            label="数量"
            width="160"
        >
          <template slot-scope="scope">
            <span>
              <el-input-number :disabled="!saveShow || index !== scope.row.rowindex" v-model="scope.row.qty" size="mini"  :min="1" label="描述文字" @change="onChangeNum(scope.row.qty,scope.row,scope.$index)"></el-input-number>
            </span>
          </template>
        </el-table-column>
        <el-table-column
            prop="marketprice"
            label="牌价"
            width="80"
        >
          <template slot-scope="scope">
            <p><span>{{scope.row.marketprice?tool.formatAmount(scope.row.marketprice,2):'--'}}</span></p>
          </template>
        </el-table-column>
        <el-table-column
            prop="discountrate"
            label="折扣(%)"
            width="100"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.discountDifferenceAmount >= 0 ">
              <p v-if="!saveShow || index !== scope.row.rowindex"><span :style="[setTopColor]">{{scope.row.discountrate}}</span></p>
              <span v-if="saveShow && index === scope.row.rowindex">
                 <el-input v-model="scope.row.discountrate" size="mini" placeholder="请输入折扣" @change="onChangeDiscountrate(scope.row.discountrate,scope.row,scope.$index)"></el-input>
              </span>
            </div>
            <div v-else-if="scope.row.discountDifferenceAmount < 0 ">
              <p v-if="!saveShow || index !== scope.row.rowindex"><span :style="[setDownColor]">{{scope.row.discountrate}}</span></p>
              <span v-if="saveShow && index === scope.row.rowindex">
                 <el-input v-model="scope.row.discountrate" size="mini" placeholder="请输入折扣" @change="onChangeDiscountrate(scope.row.discountrate,scope.row,scope.$index)"></el-input>
              </span>
            </div>
<!--            <span v-else>
              <span v-if="saveShow && index === scope.row.rowindex">
                 <el-input v-model="scope.row.discountrate" size="mini" placeholder="请输入折扣" @change="onChangeDiscountrate(scope.row.discountrate,scope.row,scope.$index)"></el-input>
              </span>
              <span v-else>
                <span >{{tool.formatAmount(scope.row.discountrate,2)}}</span>
              </span>

            </span>-->
          </template>
        </el-table-column>
        <el-table-column
            prop="price"
            label="单价"
            width="120"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.discountDifferenceAmount >= 0 ">
              <p v-if="!saveShow || index !== scope.row.rowindex"><span :style="[setTopColor]">{{tool.formatAmount(scope.row.price,2)}}</span></p>
              <span v-if="saveShow && index === scope.row.rowindex">
                <el-input v-model="scope.row.price" size="mini" placeholder="请输入单价" @change="onChangePrice(scope.row.price,scope.row,scope.$index)"></el-input>
              </span>
            </div>
            <div v-else-if="scope.row.discountDifferenceAmount < 0 " >
              <p v-if="!saveShow || index !== scope.row.rowindex"><span :style="[setDownColor]">{{tool.formatAmount(scope.row.price,2)}}</span></p>
              <span v-if="saveShow && index === scope.row.rowindex">
                <el-input v-model="scope.row.price" size="mini" placeholder="请输入单价" @change="onChangePrice(scope.row.price,scope.row,scope.$index)"></el-input>
              </span>
            </div>
<!--            <span v-else>
              <span v-if="saveShow && index === scope.row.rowindex">
                <el-input v-model="scope.row.price" size="mini" placeholder="请输入单价" @change="onChangePrice(scope.row.price,scope.row,scope.$index)"></el-input>
              </span>
               <span v-else>
                <span >{{tool.formatAmount(scope.row.price,2)}}</span>
              </span>
            </span>-->
          </template>
        </el-table-column>
        <el-table-column
            prop="discountDifferenceAmount"
            label="单价差额（元）"
            width="100"
        >
          <template slot-scope="scope">
            <p><span>{{tool.formatAmount(scope.row.discountDifferenceAmount,2)}}</span></p>
          </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?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="200">
          <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="200">
          <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="mindiscountrate"
            label="最低授权折扣(%)"
            width="80"
            >
          <template slot-scope="scope">
            <p><span>{{scope.row.mindiscountrate}}</span></p>
          </template>
        </el-table-column>

        <el-table-column
            prop="amount"
            label="金额"
            width="100"
            fixed="right">
          <template slot-scope="scope">
            <div v-if="scope.row.discountDifferenceAmount >= 0  ">
              <p ><span style="color: #79da56">{{tool.formatAmount(scope.row.amount,2)}}</span></p>
            </div>
            <div v-else-if="scope.row.discountDifferenceAmount < 0 " >
              <p><span style="color: #ef230c ">{{tool.formatAmount(scope.row.amount,2)}}</span></p>
            </div>
<!--            <p v-else><span>{{tool.formatAmount(scope.row.amount,2)}}</span></p>-->
          </template>
        </el-table-column>
        <el-table-column
            prop="specialoffer"
            label="是否特价"
            width="50"
            fixed="right">
          <template slot-scope="scope">
            <i class="el-icon-check" v-if="scope.row.discountDifferenceAmount < 0"  style="color: red;font-size: 20px"></i>
            <p v-else>--</p>
          </template>
        </el-table-column>
        <el-table-column
            prop="operation"
            fixed="right"
            label="操作"
            width="120">
          <template slot-scope="scope">
            <el-button  size="mini" type="text" class="inline-16" @click="onEdit(scope.row)" v-if="index !== scope.row.rowindex" :disabled="!tool.checkAuth($route.name,'productDetails') || data.status !== '新建' || !disabled">编 辑</el-button>
            <el-button  size="mini" type="text" class="inline-16" @click="onSave(scope.row)" v-if="saveShow && index === scope.row.rowindex">保 存</el-button>
            <el-popconfirm
                title="确定删除该产品吗?"
                @confirm="deleteProduct(scope.row)"
            >
              <el-button class="inline-16" slot="reference" size="mini" type="text"  :disabled="!tool.checkAuth($route.name,'productDetails') || data.status !== '新建' || !disabled" >删 除</el-button>
            </el-popconfirm>

<!--            <el-button  size="mini" type="text" class="inline-16" @click="saveShow = false;index = '';productData()" v-if="saveShow && index === scope.row.rowindex">取 消</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 35px;margin-top: 20px">
        <div style="float: left">总金额(元)：{{ tool.formatAmount(totalPrice,2) }}</div>
        <div style="float: right">
          <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="param.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>
</template>

<script>
import uploadFile from "@/components/upload/hw_obs_upload";
import previewImage from "@/components/previewImage";
import product_table from './productTable'
import productTableProject from "@/SDrpManagement/QuotedPrice/components/productTableProject";
import productTable from "@/SDrpManagement/QuotedPrice/components/productTable";
import addProduct from '@/template/addProduct'
import addProductProject from '@/template/addProduct'
import uploadAllData from '@/components/uploadAllData/index'
export default {
  props:["data","disabled"],
  name: "productInventory",
  components:{uploadAllData,addProductProject,addProduct,uploadFile, previewImage,product_table,productTableProject,productTable},
  data(){
    return {
      discountrate:'',
      tablecols:[],
      tablecolsAdd:[],
      list:[],
      total:0,
      currentPage:0,
      changeList:[],
      totalPrice:0,
      saveShow:false,
      index:'',
      setTopColor:{
        color:'#79da56'
      },
      setDownColor:{
        color:'#ef230c'
      },
      paramsAdd:{
        "id": 20221020164903,
        "content": {
          "sa_projectid":0,
          "sa_quotedpriceid":this.$route.query.id,
          "pageNumber": 1,
          "pageSize": 100,
          "where": {
            "condition": "",
            "tradefield":"",
            "itemclassid":"",
            "sa_brandid":"",
            "standards":""
          }

        }
      },
      paramsProjectAdd:{
        "id": 20221020164903,
        "content": {
          "sa_projectid":this.data.sa_projectid,
          "sa_quotedpriceid":this.$route.query.id,
          "pageNumber": 1,
          "pageSize": 100,
          "where": {
            "condition": "",
            "tradefield":"",
            "itemclassid":"",
            "sa_brandid":"",
            "standards":""
          }

        }
      },
      param:{
        "id": 20221021095503,
        "content": {
          "sa_quotedpriceid":'',
          "pageNumber": 1,
          "pageSize": 100,
          "where": {
            "condition": ""
          }
        }
      },
      itemids:[],
      items:[]
    }
  },
  methods:{
    /*产品配置信息*/
    async productData(){
      this.param.content.sa_quotedpriceid = this.$route.query.id
      const res = await this.$api.requested(this.param)
      this.list = res.data
      this.total = res.total
      this.totalPrice = 0
      for (var i=0 ;i<res.data.length;i++){
        this.list[i].discountrate = Math.round((res.data[i].discountrate * 100)*100)/100
        this.list[i].mindiscountrate = Math.round((res.data[i].mindiscountrate * 100) * 100)/100
        this.list[i].price = Math.round(res.data[i].price * 100)/100
        this.list[i].discountDifferenceAmount = Math.round(res.data[i].discountDifferenceAmount * 100)/100
       /* this.totalPrice = this.totalPrice + res.data[i].qty * res.data[i].price*/
      }
      if (this.total !== 0){
        this.totalPrice = Math.round(res.data[0].rowstotal[0].sumamount * 100)/100
      }
      this.$emit('productSuccess')

    },
    /*批量添加商品*/
    async addProducts(item){
      this.items = []
      this.items = item.map(e=>{
        this.discountrate = e.discountrate || this.data.discountrate.toFixed(4)
        return {
          "sa_quotedprice_itemsid":0,
          "itemid":e.itemid,
          "price":(e.marketprice * this.discountrate).toFixed(4),
          "marketprice":e.marketprice,
          "discountrate":this.discountrate,
          "qty":e.qty === ''? e.orderminqty:e.qty
        }
      })
      const res = await this.$api.requested({
        "id": 20221021095403,
        "content": {
          "sa_quotedpriceid":this.$route.query.id,     //sat_notice_classid<=0时 为新增
          "items":this.items
        }
      })
      this.tool.showMessage(res,()=>{
        this.productData()
        this.$refs.addProduct.listData()
        this.$refs.addProductProject.listData()

      })
    },
    /*单个添加商品*/
    async addProduct(item){
      this.discountrate = item.discountrate || this.data.discountrate.toFixed(4)
      const res = await this.$api.requested({
        "id": 20221021095403,
        "content": {
          "sa_quotedpriceid":this.$route.query.id,     //sat_notice_classid<=0时 为新增
          "items":[
            {
              "sa_quotedprice_itemsid":0,
              "itemid":item.itemid,
              "price":(item.marketprice * this.discountrate).toFixed(4),
              "discountrate":this.discountrate,
              "qty":item.qty === '' ? item.orderminqty : item.qty,
            }
          ]
        }
      })
      this.tool.showMessage(res,()=>{
        this.productData()
        this.$refs.addProduct.listData()
        this.$refs.addProductProject.listData()
      })
    },
    /*一键全选*/
    uploadData(uploadApi,data){
      uploadApi.id = 20221021095403
      uploadApi.content = {
        "sa_quotedpriceid": this.$route.query.id, //订单ID
        "items": data.map(e=>{
          this.discountrate = e.discountrate || this.data.discountrate.toFixed(4)
          return {
            sa_quotedprice_itemsid:0,
            itemid:e.itemid,
            qty:e.qty === '' ? e.orderminqty : e.qty,
            marketprice:e.marketprice,
            price:(e.marketprice * this.discountrate).toFixed(4),
            discountrate:this.discountrate
          }
        })
      }
      this.productData()
      this.$refs.addProduct.listData()
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.param.content.pageSize = val
      this.productData()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.param.content.pageNumber = val
      this.productData()
    },
    onSuccess(){
      this.productData()
    },
    clearData(){
      this.search = ""
      this.param.content.where.condition = this.search
      this.productData()
    },
    queryClick(){
      this.param.content.where.condition = this.search
      this.productData()
    },
    /*批量勾选*/
    selectionChange(val){
      this.itemids = []
      val.forEach((item,index)=>{
        this.itemids[index] = item.sa_quotedprice_itemsid
      })
    },
    checkForm(){
      this.$emit('checkForm')
    },
    quoterPrice(id,type){
      this.$refs.quoterPrice.queryProduct(id,type)
    },
    /*删除添加的产品*/
    async deleteProduct(val){
      const res = await this.$api.requested({
        "id": 20221021095603,
        "content": {
          "sa_quotedprice_itemsids":[val.sa_quotedprice_itemsid]     //sat_notice_classid<=0时 为新增
        }
      })
      this.tool.showMessage(res,()=>{
        this.productData()
      })
    },
    /*批量删除添加的产品*/
   deleteProducts(){
      this.$confirm('确定删除已选的产品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.$api.requested({
          "id": 20221021095603,
          "content": {
            "sa_quotedprice_itemsids":this.itemids     //sat_notice_classid<=0时 为新增
          }
        })
        this.tool.showMessage(res,()=>{
          this.productData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    /*获取要删除的数据*/
    handlePullApi (pullApi) {
      pullApi.content = JSON.parse(JSON.stringify(this.param.content))
      pullApi.id = 20221021095503
      pullApi.content.sa_quotedpriceid = this.$route.query.id
    },
    /*一键删除*/
    handleDelApi (delApi,data) {
      delApi.id = 20221021095603
      delApi.content = {
        "sa_quotedprice_itemsids":data,
        "pageNumber":0,
        "pageSize":0
      }
      this.productData()
    },
    onChangeNum (val,data,index) {
      data.qty = Math.round(val *100)/100
      data.amount = Math.round((data.qty * data.price) * 100)/100
      data.discountDifferenceAmount = Math.round((data.marketprice * (data.discountrate/100) - data.marketprice * (data.mindiscountrate/100)) * 100)/100
      this.$set(this.list,index,data)
      this.totalPrice = 0
      for (var i=0 ;i<this.list.length;i++){
        this.totalPrice = this.totalPrice + this.list[i].qty * this.list[i].price
      }
      this.totalPrice = Math.round(this.totalPrice * 100)/100
      this.$emit('productData',this.list)
    },
    onChangeDiscountrate(val,data,index) {
      data.specialoffer = 0
      if (val > 100){
        data.discountrate = 100
      }else if (val <= 0){
        data.discountrate = 1
      }else {
        data.discountrate = Math.round(val * 100)/100
      }
      data.price = Math.round((data.marketprice * (data.discountrate / 100)) *100)/100
      data.amount = Math.round((data.qty * data.price)*100)/100
      data.discountDifferenceAmount =  Math.round(( data.marketprice * (data.discountrate/100) - data.marketprice * (data.mindiscountrate/100)) * 100)/100
      if (data.discountDifferenceAmount < 0){
        data.specialoffer =1
      }
      this.$set(this.list,index,data)
      this.totalPrice = 0
      for (var i=0 ;i<this.list.length;i++){
        this.totalPrice = this.totalPrice + this.list[i].qty * this.list[i].price
      }
      this.totalPrice = Math.round(this.totalPrice * 100)/100
      this.$emit('productData',this.list)
    },
    onChangePrice(val,data,index){
      data.specialoffer = 0
      if (val > data.marketprice) {
        data.price = data.marketprice
      }else if (val < data.marketprice * 0.01){
        data.price = data.marketprice * 0.01
      }else {
        data.price = Math.round(data.price * 100)/100
      }
      data.discountrate = Math.round(((data.price / data.marketprice) * 100) *100)/100
      data.discountDifferenceAmount =  Math.round(( data.marketprice * (data.discountrate/100) - data.marketprice * (data.mindiscountrate/100)) * 100)/100
      data.amount = Math.round((data.qty * data.price)*100)/100
      if (data.discountDifferenceAmount < 0){
        data.specialoffer =1
      }
      this.$set(this.list,index,data)
      this.totalPrice = 0
      for (var i=0 ;i<this.list.length;i++){
        this.totalPrice = this.totalPrice + this.list[i].qty * this.list[i].price
      }
      this.totalPrice = Math.round(this.totalPrice * 100)/100
      this.$emit('productData',this.list)
    },
    onEdit(row){
      this.saveShow = true
      this.index = row.rowindex
    },
    async onSave(row){

      row.discountrate = (row.discountrate / 100).toFixed(4)
      const res = await this.$api.requested({
        "id": 20221021095403,
        "content": {
          "sa_quotedpriceid":this.$route.query.id,     //sat_notice_classid<=0时 为新增
          "items":[row]
        }
      })
      this.tool.showMessage(res,()=>{
        this.saveShow = false
        this.index = ''
        this.productData()
        this.$emit('productSuccess')

      })
    }
  },
  mounted() {
    this.productData()
  },
  created() {
    this.tablecolsAdd = this.tool.tabelCol(this.$route.name).addProductTable.tablecols
  }
}
</script>

<style scoped>
.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:38px;height:38px;margin:0px auto;
}
</style>