<!--
 * @Descripttion: 
 * @version: 
 * @Author: 王三华
 * @Date: 2023-12-09 09:23:53
-->
<!--
 * @Descripttion:
 * @version:
 * @Author: kBank
 * @Date: 2023-02-23 15:59:57
-->
<template>
  <div class="page">
    <div class="main">
      <div class="tit">主表</div>
      <div class="xian"></div>
      <el-form :model="ruleForm"
               :rules="rules"
               ref="ruleForm"
               class="formStyle"
               label-width="80px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="入库编号"
                          prop="orderCode">
              <el-input clearable
                        disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="供应商"
                          prop="pkCubasdoc">
              <el-select clearable
                         disabled
                         v-model="ruleForm.pkCubasdoc"
                         :placeholder="'请选择'">
                <el-option v-for="(item, index) in supplierList"
                           :key="index"
                           :label="item.custName"
                           :value="item.pkId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="采购公司"
                          prop="pkCorp">
              <el-select clearable
                         v-model="ruleForm.pkCorp"
                         disabled
                         :placeholder="'请选择'">
                <el-option v-for="(item, index) in corpList"
                           :key="index"
                           :label="item.corpName"
                           :value="item.pkId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="订单日期"
                          prop="orderDate">
              <el-date-picker v-model="ruleForm.orderDate"
                              value-format="yyyy-MM-dd"
                              type="date">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="4">
            <el-form-item label="合同号">
              <el-input clearable
                        disabled
                        v-model="ruleForm.contractCode"></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="4">
            <el-form-item label="价税合计">
              <el-input clearable
                        disabled
                        v-model="ruleForm.priceAll"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="总数量">
              <el-input clearable
                        disabled
                        v-model="ruleForm.numAll"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="备注">
              <el-input clearable
                        v-model="ruleForm.remark"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="this.isBack">
            <el-form-item label="退货原因" prop="returnReason">
              <el-input type="textarea"
                        :rows="4"
                        placeholder="请输入退货原因"
                        v-model="ruleForm.returnReason">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="tit">列表</div>
        <div class="xian"></div>
        <div v-for="(foremed,index) in ruleForm.purchaseInBParamList"
             :key="index"
             class="rowEd">
          <el-row>
            <el-col :span="4">
              <el-form-item label="产品编号"
                            :prop="`purchaseInBParamList.${index}.productCode`"
                            :rules="rules.productCode">
                <el-input clearable
                          disabled
                          @focus="getProduct(index)"
                          v-model="foremed.productCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="产品名称">
                <el-input clearable
                          disabled
                          v-model="foremed.productName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="产品规格">
                <el-input clearable
                          disabled
                          v-model="foremed.specsName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :label="'单位'"
                            :prop="`purchaseInBParamList.${index}.pkUnit`"
                            :rules="rules.pkUnit">
                <el-select clearable
                           disabled
                           v-model="foremed.pkUnit">
                  <el-option v-for="item in dwList"
                             :key="item.pkId"
                             :label="item.name"
                             :value="item.pkId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="数量"
                            :prop="`purchaseInBParamList.${index}.nnum`"
                            :rules="rules.nnum">
                <el-input clearable
                          v-model="foremed.nnum"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="仓库"
                            :prop="`purchaseInBParamList.${index}.pkStorehouse`"
                            :rules="rules.pkStorehouse">
                <el-select clearable
                           :disabled="isBack"
                           v-model="foremed.pkStorehouse">
                  <el-option v-for="item in storeList"
                             :key="item.pkId"
                             :label="item.name"
                             :value="item.pkId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="无税单价"
                            :prop="`purchaseInBParamList.${index}.norigprice`"
                            :rules="rules.norigprice">
                <el-input clearable
                          :disabled="isBack"
                          v-model="foremed.norigprice"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="税率"
                            :prop="`purchaseInBParamList.${index}.ntaxrate`"
                            :rules="rules.ntaxrate">
                <el-input clearable
                          :disabled="isBack"
                          v-model="foremed.ntaxrate"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="含税单价">
                <el-input clearable
                          disabled
                          v-model="foremed.price1"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="无税金额">
                <el-input clearable
                          disabled
                          v-model="foremed.price2"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="税额">
                <el-input clearable
                          disabled
                          v-model="foremed.price3"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="价税合计">
                <el-input clearable
                          disabled
                          v-model="foremed.price4"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="赠品"
                            :prop="`purchaseInBParamList.${index}.isGift`"
                            :rules="rules.isGift">
                <el-select v-model="foremed.isGift"
                           disabled
                           clearable>
                  <el-option v-for="item in agreeList"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="批次号"
                            :prop="`purchaseInBParamList.${index}.pkBatchCode`"
                            :rules="rules.pkBatchCode">
                <!-- <el-input clearable
                          v-model="foremed.pkBatchCode"></el-input> -->
                <el-select clearable
                           :disabled="isBack"
                           v-model="foremed.pkBatchCode">
                  <el-option v-for="item in foremed.pkBatchCodeList"
                             :key="item.pkId"
                             :label="item.batchCode"
                             :value="item.pkId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="入库时间"
                            :prop="`purchaseInBParamList.${index}.bizDate`"
                            :rules="rules.bizDate">
                <el-date-picker v-model="foremed.bizDate"
                                :disabled="isBack"
                                value-format="yyyy-MM-dd"
                                type="date">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="img"
               v-if="isBack">
            <img src="@/assets/images/iconpop.png"
                 @click="reduceProduct(index)"
                 alt="">
          </div>
        </div>
      </el-form>
      <!-- <div class="img1">
        <img src="@/assets/images/iconadd.png"
             @click="addNewGoods"
             alt="">
      </div> -->
    </div>
    <div class="footer">
      <!-- <el-button size="small"
                 class="cancelBtn"> {{ '取消' }}</el-button> -->
      <el-button size="small"
                 @click="submit('ruleForm')"
                 class="sureBtn"> {{ '确认' }}</el-button>
    </div>
    <!-- 产品弹框 -->
    <el-dialog :title="'添加'"
               :visible.sync="dialogVisible"
               :close-on-click-modal="false"
               width="50%"
               center
               :before-close="handleClose">
      <div class="cpHeight">
        <el-row>
          <el-col :span="22"> <el-input v-model="select.query"
                      clearable
                      :placeholder="'请输入'"
                      @keyup.enter.native="getDataList"
                      prefix-icon="el-icon-search"></el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="primary"
                       size="small"
                       @click="getDataList"> {{ '搜索' }}</el-button>
          </el-col>
        </el-row>
        <div style="height:10px"></div>
        <el-table :data="dialogList"
                  ref="multipleTable"
                  style="width: 100%"
                  @select-all="onSelectAll"
                  @select="selected"
                  :header-cell-style="{ background: '#EEEEEE' }"
                  :row-class-name="tableRowClassName">
          <el-table-column type="selection"
                           width="55"> </el-table-column>
          <el-table-column align="center"
                           prop="productName"
                           :label="'产品名称'">
          </el-table-column>
          <el-table-column align="center"
                           prop="productCode"
                           :label="'产品编号'">
          </el-table-column>
          <el-table-column align="center"
                           prop="productName"
                           :label="'规格'">
            <template slot-scope="scope">
              <div class="blueCor"
                   v-show="scope.row.specsName==''||scope.row.specsName==undefined"
                   @click="selSku(scope.row.productCode,scope.$index)">{{'选择规格'}}</div>
              <div class="blueCor"
                   v-show="scope.row.specsName!=''&&scope.row.specsName!=undefined"
                   @click="selSku(scope.row.productCode,scope.$index)">{{ scope.row.specsName }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           prop="unitStr"
                           :label="'单位'">
          </el-table-column>
          <el-table-column align="center"
                           prop="productName"
                           :label="'商品数量'">
            <template slot-scope="scope">
              <el-input-number size="mini"
                               v-model="scope.row.quantity"
                               :min="1"></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getDataList" />
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="handleClose">{{'取消'}}</el-button>
        <el-button type="primary"
                   @click="sureProduct">{{'确认'}}</el-button>
      </span>
    </el-dialog>
    <!-- 规格弹框 -->
    <el-dialog :title="'规格'"
               :visible.sync="ggVisible"
               :close-on-click-modal="false"
               width="40%"
               center
               :before-close="handleCloseGg">
      <el-form>
        <el-form-item :label="item.specsTypeName"
                      v-for="item,index in skuList"
                      :key="index">
          <el-radio-group v-model="item.pkProductSku">
            <el-radio v-for="ctem,cndex in item.specsList"
                      @change="getCheckBox(item.pkId,item.specsName)"
                      :key="ctem.pkSpecs"
                      :label="ctem.pkSpecs">{{ctem.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="handleCloseGg">{{'取消'}}</el-button>
        <el-button type="primary"
                   @click="sureSku">{{'确认'}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as api from '@/api/supply.js'
import * as pro from '@/api/product.js'
import * as sys from '@/api/system'

export default {
  name: 'GiftGoodsList',
  data() {
    return {
      ruleForm: {
        purchaseInBParamList: [
          {
            pkProductBas: '',
            pkStorehouse: '',
            productCode: '',
            bizDate: '',
            pkUnit: '',
            nnum: 1,
            norigprice: '',
            ntaxrate: '',
            isGift: '',
            pkBatchCode: '',
            scmItemSpecsList: [],
          },
        ],
      },
      supplierList: [],
      productList: [],
      dwList: [],
      agreeList: [],
      storeList: [],
      dialogVisible: false,
      dialogList: [], //产品数组
      select: {},
      selectData: {},
      selIndex: 0,
      selSkuList: [],
      specsName: '',
      skuList: [],
      corpList: [],
      ggVisible: false,
      queryParams: {
        pageNum: 1,
        pageSize: 50,
      },
      addOrEdit: true,
      total: 0,
      showIndex: 0,
      allData: {},
      isBack: false,
      rules: {
        pkCubasdoc: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        pkCorp: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
       
        orderDate: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        contractCode: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        productCode: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        nnum: [{ required: true, message: '请输入', trigger: 'blur' }],
        norigprice: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        ntaxrate: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        pkUnit: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        pkStorehouse: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        isGift: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        pkBatchCode: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        returnReason: [
          { required: true, message: '请输入', trigger: 'blur' },
        ],
        bizDate: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
      },
    }
  },
  watch: {
    'ruleForm.purchaseInBParamList': {
      handler(newValue, oldValue) {
        if (newValue.length > 0) {
          newValue.forEach((item) => {
            if (item.norigprice != '' && item.ntaxrate != '') {
              item.price1 = (
                item.norigprice *
                (1 + Number(item.ntaxrate) / 100)
              ).toFixed(2)
              item.price2 = (item.norigprice * item.nnum || 0).toFixed(2)
              item.price3 = (
                (item.norigprice * (item.nnum || 0) * item.ntaxrate) /
                100
              ).toFixed(2)
              item.price4 = (
                item.norigprice *
                  (1 + Number(item.ntaxrate) / 100) *
                  item.nnum || 0
              ).toFixed(2)
            }
          })
          let a = 0,
            b = 0
          newValue.forEach((item) => {
            if (item.norigprice != '' && item.ntaxrate != '') {
              a += Number(item.nnum)
              b += Number(item.price4)
            }
          })
          this.ruleForm.priceAll = b
          this.ruleForm.numAll = a
        }
      },
      deep: true,
    },
  },
  mounted() {
    if (this.$route.query.data) {
      this.allData = JSON.parse(this.$route.query.data)[0]
      this.addOrEdit = this.$route.query.addOrEdit || false
      if (this.addOrEdit) {
        this.allData.purchaseInBParamList = this.allData.childArr
        delete this.allData.childArr
        delete this.allData.scmReturnbVoList
        delete this.allData.pkId
        this.allData.purchaseInBParamList.forEach((item) => {
          delete item.pkId
        })
      } else {
        this.allData.purchaseInBParamList = this.allData.icPurchaseInbList
        delete this.allData.icPurchaseInbList
        this.isBack = this.$route.query.isBack ? true : false
      }
      this.ruleForm = this.allData
      this.ruleForm.purchaseInBParamList.forEach((item) => {
        this.getCodeList(item)
      })
      this.getStore()
    }

    this.getData()
  },
  methods: {
    getData() {
      api.supplierList().then((res) => {
        this.supplierList = res.rows
      })
      api.getEYesNoList().then((res) => {
        this.agreeList = res.data
      })
      pro.unitAll().then((res) => {
        this.dwList = res.data
      })
      // sys.getStoreHouseList().then((res) => {
      //   this.storeList = res.rows
      // })
      api.corpList().then((res) => {
        this.corpList = res.rows
      })
    },
    getCodeList(item) {
      api
        .batchRefer({
          pkProduct: item.pkProduct,
        })
        .then((res) => {
          this.$nextTick(() => {
            this.$set(item, 'pkBatchCodeList', res.rows)
          })
        })
    },
    getStore() {
      api
        .getStoreRefer({
          pkCorp: this.ruleForm.pkCorp,
        })
        .then((res) => {
          this.storeList = res.rows
        })
    },
    getDataList() {
      api
        .productFind(Object.assign({pkCubasdoc:this.ruleForm.pkCubasdoc}, this.queryParams, this.select))
        .then((res) => {
          res.rows.forEach((item) => {
            item.quantity = 1
          })
          this.dialogList = res.rows
          this.total = res.total
        })
    },
    getProduct(index) {
      this.showIndex = index
      this.getDataList()
      this.dialogVisible = true
    },
    reduceProduct(index) {
      this.ruleForm.purchaseInBParamList.splice(index, 1)
      this.$forceUpdate()
    },
    addNewGoods() {
      this.ruleForm.purchaseInBParamList.push({
        pkProductBas: '',
        productCode: '',
        pkStorehouse: '',
        bizDate: '',
        pkUnit: '',
        nnum: 1,
        norigprice: '',
        ntaxrate: '',
        isGift: '',
        pkBatchCode: '',
        scmItemSpecsList: [],
      })
    },
    handleCloseGg() {
      this.ggVisible = false
    },
    selSku(productCode, index) {
      this.selIndex = index
      api
        .productFindInfo({
          productCode: productCode,
        })
        .then((res) => {
          let arr1 = [],
            arr2 = []
          res.data.productBasSpecsList.forEach((item) => {
            item.pkProductSku = item.specsList[0].pkSpecs
            arr1.push({
              pkSpecs: item.specsList[0].pkSpecs,
              pkSpecsType: item.pkSpecsType,
            })
            arr2.push(item.specsList[0].name)
          })
          this.selSkuList = arr1
          this.specsName = arr2.join(',')

          this.skuList = res.data.productBasSpecsList
          this.ggVisible = true
        })
    },
    getCheckBox() {
      let arr1 = [],
        arr2 = []
      this.skuList.forEach((item) => {
        item.specsList.forEach((ctem) => {
          if (ctem.pkSpecs == item.pkProductSku) {
            arr1.push({
              pkSpecs: ctem.pkSpecs,
              pkSpecsType: item.pkSpecsType,
            })
            arr2.push(ctem.name)
          }
        })
      })
      this.selSkuList = arr1
      this.specsName = arr2.join(',')
    },
    handleClose() {
      this.selectData = []
      this.dialogVisible = false
    },
    onSelectAll() {
      this.$refs.multipleTable.clearSelection()
    },
    selected(selection, row) {
      this.$refs.multipleTable.clearSelection()
      if (selection.length == 0) return
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.selectData = row
    },
    sureProduct() {
      if (this.selectData.length == 0) {
        this.$message({
          message: '请选择产品',
          type: 'warning',
        })
        return false
      } else {
        console.log(
          '%c [   this.selectData ]-490',
          'font-size:13px; background:#50a5a4; color:#94e9e8;',
          this.selectData
        )
        this.ruleForm.purchaseInBParamList[this.showIndex].productCode =
          this.selectData.productCode
        this.ruleForm.purchaseInBParamList[this.showIndex].pkProductBas =
          this.selectData.pkId
        this.ruleForm.purchaseInBParamList[this.showIndex].productName =
          this.selectData.productName
        this.ruleForm.purchaseInBParamList[this.showIndex].specsName =
          this.selectData.specsName
        this.ruleForm.purchaseInBParamList[this.showIndex].pkUnit =
          this.selectData.unit
        this.ruleForm.purchaseInBParamList[this.showIndex].nnum =
          this.selectData.quantity
        this.ruleForm.purchaseInBParamList[this.showIndex].scmItemSpecsList =
          this.selectData.selSkuList
        this.handleClose()
        this.$forceUpdate()
      }
    },
    sureSku() {
      this.$set(this.dialogList[this.selIndex], 'selSkuList', this.selSkuList)
      this.$set(this.dialogList[this.selIndex], 'specsName', this.specsName)
      this.ggVisible = false
    },
    submit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let url
          if (this.addOrEdit) {
            url = api.purchaseInsert
          } else {
            if (this.isBack) {
              url = api.purOutBack
            } else {
              url = api.purchaseUpdate
            }
          }
          url(this.ruleForm).then((res) => {
            if (res.code == 200) {
              this.$message({
                message: res.msg,
                type: 'success',
              })
              this.$router.go(-1)
            }
          })
        }
      })
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return 'warning-row'
      } else if (rowIndex % 2 == 0) {
        return 'success-row'
      }
      return ''
    },
  },
}
</script>

<style lang="scss" scoped>
.page {
  padding: 20px;
  background: #f9f9f9;
  font-size: 14px;
  .main_a {
    height: calc(100vh - 144px);
    display: flex;
    flex-direction: column;
  }
  .main {
    background: #ffffff;
    border-radius: 8px;
    // height: calc(100vh - 124px);
    box-shadow: 0px 2px 20px 0px rgba(238, 238, 238, 0.5);
    overflow-x: hidden;
  }
  ::v-deep .el-select {
    width: 100%;
  }
}
.footer {
  height: 68px;
  background: #ffffff;
  box-shadow: 0px -3px 20px 0px rgba(204, 204, 204, 0.5);
  // margin: 0 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  .thebtn1 {
    background: #3181e5;
    color: #ffffff;
    padding: 9px 45px;
  }
  .thebtn2 {
    background: #cccccc;
    color: #ffffff;
    padding: 9px 45px;
  }
}
.tit {
  font-size: 14px;
  font-weight: bold;
  color: #333333;
  padding: 0 20px;
  border-left: 5px solid #c8161d;
  margin: 20px 0 10px 0;
}
.xian {
  height: 1px;
  background: rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}
.demo-ruleForm {
  padding: 10px 0px;
}
::v-deep .el-date-editor--datetimerange {
  width: auto !important;
}
.flexed {
  display: flex;
}
.flexed_l {
  margin-right: 20px;
}
.topbox {
  align-items: center;
  padding: 0px 0 15px 0;
  display: flex;
  //   background: skyblue;
  .levelList_i {
    margin-left: 20px;
    position: relative;
    cursor: pointer;
    padding: 0 5px;
    width: 88px;
    height: 34px;
    border-radius: 17px;
    border: 1px solid #cccccc;
    font-size: 14px;
    font-family: MicrosoftYaHei;
    text-align: center;
    line-height: 32px;
  }
  .act {
    color: #ffffff;
    background: #c8161d;
  }
}
::v-deep .el-form-item {
  margin-bottom: 20px !important;
}
::v-deep .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100% !important;
}
.blueCor {
  color: #589ff8;
  cursor: pointer;
}
::v-deep .el-input__icon {
  line-height: 33px;
}
::v-deep .el-button {
  margin-top: 0;
}
.formStyle {
  padding-right: 10px;
}
.rowEd {
  border-bottom: 5px solid rgba(0, 0, 0, 0.1);
  margin: 10px 0;
}
.img {
  text-align: center;
  margin-bottom: 10px;
  img {
    width: 25px;
    height: 25px;
  }
}
.img1 {
  text-align: center;
  padding-right: 10px;
  img {
    width: 25px;
    height: 25px;
  }
}
</style>
