
<template>
  <div>
    <div style="margin-bottom: 15px">
      <addProduct ref="addProduct" @uploadData="uploadData" @closeDrawer="listData"
                  :tradefield="data.tradefield" v-if="tool.checkAuth($route.name,'productSetManage') && data.disabled"
                  class="inline-16" :params="paramsAdd" title="添 加"
                  @addSuccess="addProducts" :discountrate="discountrate" @addProduct="addProduct" :tablecolsAdd="tablecolsAdd"
      ></addProduct>
      <uploadAllData
          v-if="tool.checkAuth($route.name,'productSetManage') && data.disabled"
          class="inline-16"
          :total="total"
          @onSuccess="listData()"
          @handlePullApi="handlePullApi"
          @handleDelApi="handleDelApi"
          idName="sa_project_itemsid"
          type="del"
      ></uploadAllData>
      <el-button  v-if="tool.checkAuth($route.name,'productSetManage') && data.disabled" class="inline-16" size="small" :type="delProductData.length === 0?'':'primary'" @click="onDelProduct" :disabled="delProductData.length === 0">删 除</el-button>
      <el-input
          size="small"
          style="width: 200px;"
          :suffix-icon="params.content.where.condition?params.content.where.condition.length > 0?'':'':'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 style="float: right">
        <label class="search__label">预计折扣(%):</label>
        <el-input style="width: 100px;" v-model="discountrate" size="small"   label="默认折扣"  :disabled="!tool.checkAuth($route.name,'productSetManage') || !data.disabled" @change="discountrateChange(discountrate)"></el-input>
      </div>
    </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="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="material"
            label="装置"
            width="180">
          <template slot-scope="scope">
            <p><span>{{scope.row.device || '--'}}</span></p>
          </template>
        </el-table-column>
        <el-table-column
            prop="material"
            label="产线"
            width="180">
          <template slot-scope="scope">
            <p><span>{{scope.row.prodline || '--'}}</span></p>
          </template>
        </el-table-column>
        <el-table-column
            prop="material"
            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="100">
          <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="qty"
            label="数量"
            fixed="right"
            width="180">
          <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)" :disabled="!data.disabled"></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"    @change="priceChange(scope.row.price,scope.$index,scope.row)" :disabled="!data.disabled"></el-input>
          </template>
        </el-table-column>
        <el-table-column
            prop="amount"
            label="金额(元)"
            fixed="right"
            width="100">
          <template slot-scope="scope">
            <p><span>{{scope.row.amount?tool.formatAmount(scope.row.amount,2):'--'}}</span></p>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top:16px;">
        <div style="float: left">
          <span>金额(元)：{{totalPrice?tool.formatAmount(totalPrice,2):'0.00'}}</span>
        </div>
        <div style="float: 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>
</template>

<script>
import add from './add'
import addProduct from '@/template/addProduct'
import edit from "@/HDrpManagement/projectChange/modules/modules/andEnterprise/components/edit";
import to_del from "@/HDrpManagement/projectChange/modules/modules/andEnterprise/components/toDel";
import uploadFile from "@/components/upload/hw_obs_upload";
import previewImage from "@/components/previewImage";
import delete_product from './deleteProduct'
import uploadAllData from '@/components/uploadAllData/index'
export default {
  props:["data"],
  components:{add,uploadAllData,addProduct,uploadFile, previewImage,delete_product},
  data () {
    return {
      tableHieght:"860px",
      totalPrice:0,
      tablecols:[],
      tablecolsAdd:[],
      list:[],
      total:0,
      currentPage:0,
      search:'',
      options:[],
      productList:'',
      delProductData:[],
      discountrate:'',
      paramsAdd:{
        "id": 20221021171802,
        "content": {
          "sa_projectid": this.$route.query.id,
          "pageNumber": 1,
          "pageSize": 100,
          "where": {
            "condition": "",
            "tradefield": "",
            "standards": "",
            "itemclassid": "",
            "sa_brandid": "",
            "model":"",
            "spec":"",
            "material":''
          }
        },
      },
      params:{
        "id": 20221021145702,
        "content": {
          "sa_projectid": this.$route.query.id,
          "pageNumber": 1,
          "pageSize": 100,
          "where": {
            "condition": ""
          }
        },
      },
      items:[]
    }
  },
  provide () {
    return {
      productList:() => this.productList
    }
  },
  methods:{
    /*list (vm) {
      vm.content.sa_projectid = this.$route.query.id
    },*/

    async listData(){
      console.log("成功")
      this.discountrate = Math.round((this.data.discountrate * 100) * 100) / 100
      this.totalPrice = 0
      this.params.content.sa_projectid = this.data.sa_projectid
      const res = await this.$api.requested(this.params)
      this.list = res.data
      res.data.forEach((e,index)=>{
        this.list[index].price = this.list[index].price.toFixed(2)
      })
      this.totalPrice = res.tips.amount
      this.total = res.total
      this.$emit("delSuccess")
    },
    uploadData (uploadApi,data) {
      uploadApi.id = 20221021145502
      uploadApi.content = {
        "sa_projectid": this.$route.query.id, //订单ID
        "items": data.map(e=>{
          return {
            sa_project_itemsid:0,
            itemid:e.itemid,
            qty:e.orderminqty,
            remarks:e.remarks,
            marketprice:e.marketprice,
            price:(e.marketprice * (this.discountrate / 100)).toFixed(4)
          }
        })
      }
    },
    handlePullApi (pullApi) {
      pullApi.content = JSON.parse(JSON.stringify(this.params.content))
      pullApi.id = 20221021145702
      pullApi.content.sa_projectid = this.$route.query.id
    },
    handleDelApi (delApi,data) {
      delApi.id = 20221021145602
      delApi.content = {
        "deletereason": "",
        "sa_projectid":this.$route.query.id,
        "sa_project_itemsids":data,
        "pageNumber":0,
        "pageSize":0
      }
      this.listData()
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params.content.pageSize = val
      this.listData()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.params.content.pageNumber = val
      this.listData()
    },
    async addProducts(items){
      console.log(items,'商品明细')
      this.items = []
      this.items = items.map(e=>{
        return {
          sa_project_itemsid:0,
          itemid:e.itemid,
          qty:e.orderminqty,
          remarks:e.remarks,
          marketprice:e.marketprice,
          price:(e.marketprice * (this.discountrate / 100)).toFixed(4)
        }
      })
      const res = await this.$api.requested({
        "id": 20221021145502,
        "content": {
          "sa_projectid": this.$route.query.id,
          "items": this.items
        },
      })
      this.$refs.addProduct.listData()
      this.listData()
    },
    async addProduct(items){
      console.log(items,'商品明细')
      const res = await this.$api.requested({
        "id": 20221021145502,
        "content": {
          "sa_projectid": this.$route.query.id,
          "items": [
            {
              "sa_project_itemsid":0,
              "itemid": items.itemid,
              "qty": items.orderminqty,
              "remarks": "",
              "marketprice":items.marketprice,
              "price":(items.marketprice * (this.discountrate / 100)).toFixed(4)
            }
          ]
        },
      })
      this.$refs.addProduct.listData()
      this.listData()
    },
    onSuccess(){
      this.listData()
      this.$emit("productSetSuccess")
    },
    clearData(){
      this.search = ""
      this.params.content.where.condition = this.search
      this.listData()
    },
    queryClick(){
      this.params.content.where.condition = this.search
      this.listData()
    },
    selectionChange(val){
      this.delProductData = []
      val.forEach((item,index) => {
        this.delProductData[index] = item.sa_project_itemsid
      })
    },
    onDelProduct() {
      this.$confirm('此操作将删除这些商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delProduct()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        });
      });
    },
    /*批量删除商品*/
    async delProduct(){
      const res = await this.$api.requested({
        "id": 20221021145602,
        "content": {
          "deletereason": "",
          "sa_projectid":this.data.sa_projectid,
          "sa_project_itemsids":this.delProductData
        },
      })
      this.tool.showMessage(res,()=>{
        this.listData()
        this.$emit("delSuccess")
      })
    },
    /*修改商品数量*/
    numChange(val,index,data){
      data.qty = val.toFixed(2)
      data.amount = (data.price * data.qty).toFixed(2)
      this.$set(this.list,index,data)
      this.onChangQty(data,data.qty)
    },
    /*修改单价*/
    priceChange(val,index,data){
      if (val > data.marketprice){
        data.price = this.tool.formatAmount(data.marketprice,2)
      }else if(val < 0) {
        data.price = 0
      }else {
        data.price = this.tool.formatAmount(val ,2)
      }
      data.amount = this.tool.formatAmount(data.price * data.qty,2)
      this.$set(this.list,index,data)
      this.onChangePrice(data,data.price)
    },
    /*执行修改数量*/
    async onChangQty(data,val){
      const res = await this.$api.requested({
        "id": 20221021145502,
        "content": {
          "sa_projectid": this.data.sa_projectid,
          "items": [
            {
              "sa_project_itemsid":data.sa_project_itemsid,
              "itemid": data.itemid,
              "qty": val,
              "remarks": "",
              "marketprice": data.marketprice, //市场价
              "price": data.price //单价
            }
          ]
        }
      })
      this.listData()
      this.$emit("productSetSuccess")
    },
    /*执行修改单价*/
    async onChangePrice(data,val){
      const res = await this.$api.requested({
        "id": 20221021145502,
        "content": {
          "sa_projectid": this.data.sa_projectid,
          "items": [
            {
              "sa_project_itemsid":data.sa_project_itemsid,
              "itemid": data.itemid,
              "qty": data.qty,
              "remarks": "",
              "marketprice": data.marketprice, //市场价
              "price": val //单价
            }
          ]
        }
      })
      this.listData()
      this.$emit("productSetSuccess")
    },
    /*修改预计折扣*/
    async discountrateChange(val){
      if (val > 100){
        this.discountrate = 100
      }else if(val < 0){
        this.discountrate = 0
      }else {
        this.discountrate = Math.round(val * 100)/100
      }
     /* this.discountrate = (this.discountrate / 100).toFixed(4)*/
      const res = await this.$api.requested({
        "id": 20230207090702,
        "content": {
          "sa_projectid": this.$route.query.id,
          "discountrate": (this.discountrate / 100).toFixed(4)
        },
      })
      this.tool.showMessage(res,()=>{
        this.data.discountrate = this.discountrate / 100
        this.$emit("productSetSuccess")
        this.listData()
      })
    }
  },
  created() {
    /*this.getProductList()*/
    /*this.tablecols = this.tool.tabelCol(this.$route.name).projectSetTable.tablecols*/
    this.tablecolsAdd = this.tool.tabelCol(this.$route.name).addProductTable.tablecols
   /* this.data.discountrate = Math.round((this.data.discountrate * 100) * 100) / 100*/
  },
  mounted () {
    this.listData()
  }
}

</script>
<style scoped>
/* /deep/.el-table__cell .cell {
  display: flex;
  justify-content: s;
} */
.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>