<template>
    <div v-loading="loading">
        <div class="white-box">
            <el-form ref="form"  label-width="auto" class="form-page">
                <el-form-item :label="$t('shop.productName')"><!-- 商品名称 -->
                    <el-input v-model="form.goodsName"></el-input>
                </el-form-item>
                <el-form-item :label="$t('shop.memberDiscount')"><!-- 会员折扣 -->
                    <el-input v-model="form.sellDiscount"></el-input>
                </el-form-item>
                <el-form-item :label="$t('shop.productType')"><!-- 商品类型 -->
                    <el-checkbox  v-for="(value,key) in GiftTypeArr" v-model="form.giftType[key-1]" :key="key" >{{value.name}}</el-checkbox>
                </el-form-item>
                <el-form-item :label="$t('shop.productCode')"><!-- 商品编号 -->
                    <el-input v-model="form.goodsNo"></el-input>
                </el-form-item>
                <el-form-item :label="$t('shop.unit')"><!-- 单位 -->
                    <el-input v-model="form.unit"></el-input>
                </el-form-item>
                <el-form-item :label="$t('shop.standardPrice')">
                    <el-input-number v-model="form.sellPriceStandard" @input="handleInput" class="left-aligned-input" :precision="2" :step="0.1" :min="0" :controls="false" style="text-align: left"></el-input-number>
                </el-form-item>
                <el-form-item :label="$t('shop.priceBV')" v-show="pvDisabled"><!-- 价格BV -->
                    <el-input v-model="form.pricePv"></el-input>
                </el-form-item>
                <el-form-item :label="$t('shop.availableCountries')"><!-- 可购买国家 -->
                  <el-button type="primary" size="small" :disabled="!form.sellPriceStandard" @click="editAvailableCountries">{{ $t('shop.modifyAvailableCountries') }}</el-button>
                </el-form-item>
              <el-form-item :label="$t('shop.AutoMaintenance')"> <!-- 自动分期 -->
                <el-switch
                    v-model="form.autoMaintenance"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-value="1"
                    inactive-value="0">
                </el-switch>
              </el-form-item>
                <el-form-item :label="$t('shop.inventory')"><!-- 库存 -->
                    <el-input v-model="form.storeNums"></el-input>
                </el-form-item>
                <el-form-item :label="$t('shop.productDetails')"><!-- 商品详情 -->
                    <el-input
                            type="textarea"
                            :rows="2"
                            :placeholder="$t('shop.enterContentNotice')"
                            v-model="form.content">
                    </el-input><!-- 请输入内容 -->
                </el-form-item>
                <el-form-item :label="$t('shop.order')"><!-- 排序 -->
                    <el-input v-model="form.sort"></el-input>
                </el-form-item>
                <el-form-item :label="$t('shop.uploadImages')"><!-- 上传图片 -->
                    <div class='up_load'>
                        <Upload
                            :request-route="'v1/shop/upload'"
                            width="400px"
                            height="160px"
                            @on-success="upLoadSuccess"
                            ></Upload>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addSubmit" :loading="submitButtonStat">{{ $t('table.add') }}<!-- 添加 --></el-button>
                </el-form-item>
            </el-form>
        </div>
      <el-dialog :title="$t('shop.modifyAvailableCountries')" :visible.sync="editAvailableCountriesDialog" top="3%" width="60%"><!-- 修改可购买国家 -->
        <el-form ref="form"  label-width="130px" class="">
          <el-form-item :label="$t('shop.productName')"><!-- 商品名称 -->
            <el-input v-model="form.goodsName" disabled></el-input>
          </el-form-item>
          <el-form-item :label="$t('transportationConfig.countryName')">
            <el-input
              v-model="searchQuery"
              placeholder=""
              @input="updateTableData"
            ></el-input>
          </el-form-item>
        </el-form>

        <el-form :model="availableCountriesTableForm" ref="availableCountriesTableForm" :rules="rules">
          <el-table v-show="!searchQuery" :data="availableCountriesTableForm.availableCountriesList" ref="multipleTable" @row-click="handleRowClick" @selection-change="handleSelectionChange" @select="selectOne" :selectable="isRowSelectable" :header-cell-class-name="cellClass" stripe height="500" style="width: 100%;">
            <el-table-column
                type="selection"
                width="55"
                :selectable="selectable"
                :show-select-all="false"
            >
            </el-table-column>
            <el-table-column prop="NAME" :label="$t('transportationConfig.countryName')" />
            <el-table-column prop="LOCAL_CURRENCY_NAME" :label="$t('exchangeRateConfig.currencyType')" />
            <el-table-column :label="$t('shop.salesPrice')" min-width="100px;">
              <template slot-scope="scope">
                <el-form-item :prop="`availableCountriesList.${scope.$index}.sellPrice`" >
                  <el-input-number v-model="scope.row.sellPrice" :controls="false"></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('shop.marketPrice')" min-width="100px;">
              <template slot-scope="scope">
                <el-form-item :prop="`availableCountriesList.${scope.$index}.marketPrice`">
                  <el-input-number v-model="scope.row.marketPrice" :precision="2" :min="0" :controls="false" clearable></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('shop.taxRate')" min-width="100px;">
              <template slot-scope="scope">
                  <el-form-item :prop="`availableCountriesList.${scope.$index}.taxRate`" >
                    <div class="flexJfAc">
                      <el-input-number v-model="scope.row.taxRate" :precision="2" :step="0.1" :min="0" :controls="false"></el-input-number><span>%</span>
                    </div>
                  </el-form-item>
              </template>
            </el-table-column>
          </el-table>

          <el-table v-show="searchQuery" :data="availableCountriesTableForm.tempData" ref="multipleTableTemp" @row-click="handleRowClickTemp" @selection-change="handleSelectionChangeTemp" @select="selectOneTemp" :selectable="isRowSelectable" :header-cell-class-name="cellClass" stripe height="500" style="width: 100%;">
            <el-table-column
                type="selection"
                width="55"
                :selectable="selectable"
                :show-select-all="false"
            >
            </el-table-column>
            <el-table-column prop="NAME" :label="$t('transportationConfig.countryName')" />
            <el-table-column prop="LOCAL_CURRENCY_NAME" :label="$t('exchangeRateConfig.currencyType')" />
            <el-table-column :label="$t('shop.salesPrice')" min-width="100px;">
              <template slot-scope="scope">
                <el-form-item :prop="`tempData.${scope.$index}.sellPrice`" >
                  <el-input-number v-model="scope.row.sellPrice" :controls="false" disabled></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('shop.marketPrice')" min-width="100px;">
              <template slot-scope="scope">
                <el-form-item :prop="`tempData.${scope.$index}.marketPrice`">
                  <el-input-number v-model="scope.row.marketPrice" :precision="2" :min="0" :controls="false" clearable></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('shop.taxRate')" min-width="100px;">
              <template slot-scope="scope">
                <el-form-item :prop="`tempData.${scope.$index}.taxRate`" >
                  <div class="flexJfAc">
                    <el-input-number v-model="scope.row.taxRate" :precision="2" :step="0.1" :min="0" :controls="false"></el-input-number><span>%</span>
                  </div>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>

        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="mini" @click="editAvailableCountriesDialog = false">{{ $t('table.cancel') }}</el-button>
          <el-button type="primary" size="mini" @click="submitAvailableCountries">{{ $t('table.confirm') }}</el-button>
        </div>

      </el-dialog>
    </div>
</template>

<script>
import { addGoods, getAddGoodsConfig, getUploadToken } from '@/api/shop'
import { getCountries } from "@/api/site"
import Upload from '@/components/Upload'
import baseInfo from '@/utils/baseInfo'

export default {
  name: 'goods-add',
  components: {Upload},
  mounted () {
    this.getData()
    this.getFileToken()
  },
  data () {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      loading: false,
      file: null,
      uploadToken: '',
      pvSplitOptions: [
        {
          value: '0',
          label: this.$t('common.no')
        },
        {
          value: '1',
          label: this.$t('common.yes')
        }],
      form: {
        goodsName: '',
        type: '',
        giftType: [false, false, false, false],
        sellType: [false, false],
        goodsNo: '',
        unit: '',
        marketPrice: '',
        sellPrice: '',
        pvSplit: '0',
        pricePv: '',
        point: '',
        storeNums: '',
        content: '',
        sort: '',
        discount: '',
        cover: '',
        textarea: '',
        sellDiscount: '',
        categoryType: 1,
        sellPriceStandard: undefined,
        taxRate: 0,
        nature: [],
        autoMaintenance: '1',
      },
      submitButtonStat: false,
      goodsType: [],
      GiftTypeArr: [],
      categoryType: [],
      sellType: null,
      countries: [],
      width: '100px',
      height: '100px',
      pvDisabled: true,
      exchangeRate: baseInfo.exchangeRate(),
      editAvailableCountriesDialog: false,
      availableCountriesTableForm: {
        availableCountriesList: [],
        tempData:[],
      },
      multipleSelection: [],
      multipleSelectionTemp: [],

      rules: {},
      rulesTemp: {},
      searchQuery: '',

      selectionTempData: [],
      selectedIds: [], // 存储选中的项的 ID
      selectedIdsTemp: [],
    }
  },
  watch: {
    dialogVisible (newVal, oldVal) {
      console.log(newVal, oldVal)
    },
    // 监听商品分类,控制PV是否展示
    'form.categoryType': {
      deep: true,
      handler (modern, origin) {
        this.pvDisabled = (parseInt(modern) === 1)
      }
    },
    // 监听商品标准价格,自动计算销售价格
    'form.sellPriceStandard': {
        deep: true,
        handler(modern, origin) {
          if(modern){
            this.form.nature = []
            this.availableCountriesTableForm.availableCountriesList = []
            this.toggleSelection(this.form.nature)
          }
        }
    },
  },
  computed: {
    filteredData() {
      if (!this.searchQuery) {
        return this.availableCountriesTableForm.availableCountriesList;
      }
      const query = this.searchQuery.toLowerCase();
      // this.$refs.multipleTable.toggleRowSelection(JSON.parse(JSON.stringify(this.multipleSelection)),true)
      return this.availableCountriesTableForm.availableCountriesList.filter(row => {
        return row.NAME.toLowerCase().includes(query);
      });

    }
  },
  methods: {
    updateTableData() {
      // if (!this.searchQuery) {
      //   return this.availableCountriesTableForm.availableCountriesList;
      // }
      // 临时存储原始数据，保持搜索时不改变其他列的值
      const query = this.searchQuery.toLowerCase();
      // this.$refs.multipleTable.toggleRowSelection(JSON.parse(JSON.stringify(this.multipleSelection)),true)

      if (this.availableCountriesTableForm.tempData.length === 0) {
        // this.availableCountriesTableForm.tempData = JSON.parse(JSON.stringify(this.availableCountriesTableForm.availableCountriesList));
        // this.selectionTempData = JSON.parse(JSON.stringify(this.multipleSelection));

      }
      // const query = this.searchQuery.toLowerCase();
      this.$nextTick(() => {
        // 在数据更新后，重新设置选中的项
        if(!this.searchQuery){
          this.setSelectionTemp();
        } else {
          this.availableCountriesTableForm.tempData = this.availableCountriesTableForm.availableCountriesList.filter(row => {
            // const originalRow = this.availableCountriesTableForm.availableCountriesList.find(item => item.NAME === row.NAME);
            // console.log(originalRow);
            //
            return row.NAME.toLowerCase().includes(query);
          });
          this.setSelection();

        }
      });
      // this.availableCountriesTableForm.availableCountriesList.forEach(row => {
      //   if (row.NAME.toLowerCase().includes(query)) {
      //   } else {
      //     const originalRow = this.filteredData.find(item => item.NAME === row.NAME);
      //     if (originalRow) {
      //       if(originalRow.selected === true){
      //         console.log('originalRow true')
      //       }
      //       row = originalRow;
      //
      //     }
      //   }
      // });
      // this.$refs.multipleTable.toggleRowSelection(this.selectionTempData)

    },
    setSelection() {
      this.availableCountriesTableForm.tempData.forEach(row => {
        if (this.selectedIds.includes(row.ID)) {
          this.$nextTick(() => {
            this.$refs.multipleTableTemp.toggleRowSelection(row, true);
          });
        }
      });
    },
    setSelectionTemp() {
      // this.$refs.multipleTable.clearSelection();
      let selectedIds = JSON.parse(JSON.stringify(this.selectedIds))
      let selectedIdsTemp = JSON.parse(JSON.stringify(this.selectedIdsTemp))

      let list = selectedIds.concat(selectedIdsTemp)
      this.availableCountriesTableForm.availableCountriesList.forEach(row => {
        if (list.includes(row.ID)) {
          this.$refs.multipleTable.toggleRowSelection(row, true);
        }
      });
    },
    handleRowClick(row) {
      console.log(row)

      // 手动控制行点击时的选中状态
      // this.$refs.multipleTable.toggleRowSelection(row,true);
    },
    handleRowClickTemp(row) {
      console.log(row)
      console.log('temp 选中')
      // 手动控制行点击时的选中状态
      // this.$refs.multipleTableTemp.toggleRowSelection(row,true);
    },

    handleInputBlur(row) {
      // 当输入框失去焦点时，将修改应用到原始数据
      let originalRow = this.availableCountriesTableForm.tempData.find(item => item.NAME === row.NAME);
      if (originalRow) {
        originalRow = row;
      }
    },
      handleInput(value) {
          // console.log(value)
          // if (value < 0 || value === 0) {
          //     this.form.sellPriceStandard = "";
          // }
      },
    // 隐藏表头中的全选框
    cellClass(row) {
      if (row.columnIndex === 0) {
        return 'disabledCheck'
      }
    },
    isRowSelectable(row, index) {
      return row.CURRENCY_PRODUCT_RATE == 0;
    },
    selectable(row, index) {
      return row.CURRENCY_PRODUCT_RATE !== 0;
    },

    taxRateInput(scope){
      // 检查输入值是否为正数
      const value = scope.row.taxRate
      if (value > 0) {
        let moment = this.availableCountriesTableForm.availableCountriesList[scope.$index]
        this.$set(this.availableCountriesTableForm.availableCountriesList,scope.$index, moment)
      } else {
        scope.row.taxRate = ''; // 更新输入框的值
      }

    },
    marketPriceInput(scope){
      const value = scope.row.marketPrice
      if (value > 0) {
        let moment = this.availableCountriesTableForm.availableCountriesList[scope.$index]
        this.$set(this.availableCountriesTableForm.availableCountriesList,scope.$index, moment)
      } else {
        scope.row.marketPrice = ''; // 更新输入框的值

      }
    },
    edit(){

    },
    submitAvailableCountries(){
      this.$refs.availableCountriesTableForm.validate((valid) => {
        if (valid) {
          this.form.nature = this.multipleSelection
          this.editAvailableCountriesDialog = false
        } else {

          return false;
        }
      });

    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // 更新选中的项
      this.selectedIds = val.map(item => item.ID);
      this.updateRules();
    },
    handleSelectionChangeTemp(val) {
      this.multipleSelectionTemp = val;
      // 更新选中的项
      this.selectedIdsTemp = val.map(item => item.ID);
      this.updateRulesTemp();
    },
    updateRules() {
      this.rules = {}; // 重置规则
      this.multipleSelection.forEach((row, index) => {
        this.rules[`availableCountriesList.${this.availableCountriesTableForm.availableCountriesList.indexOf(row)}.taxRate`] = [
          { required: true, message: this.$t('shop.enterTaxRate'), trigger: 'blur' }
        ];

      });
    },
    updateRulesTemp() {
      this.rules = {}; // 重置规则
      this.multipleSelectionTemp.forEach((row, index) => {
        this.rules[`tempData.${this.availableCountriesTableForm.tempData.indexOf(row)}.taxRate`] = [
          { required: true, message: this.$t('shop.enterTaxRate'), trigger: 'blur' }
        ];

      });
    },
    selectOne(selection,row){
      row.sellPrice = (row.CURRENCY_PRODUCT_RATE * this.form.sellPriceStandard).toFixed(2)
      row.marketPrice = (row.sellPrice * 1.2).toFixed(2)
    },
    selectOneTemp(selection,row){
      row.sellPrice = (row.CURRENCY_PRODUCT_RATE * this.form.sellPriceStandard).toFixed(2)
      row.marketPrice = (row.sellPrice * 1.2).toFixed(2)
    },
    editAvailableCountries(){
      this.availableCountriesTableForm.availableCountriesList = this.countries
      this.editAvailableCountriesDialog = true
      this.toggleSelection(this.form.nature)

      // getCountries({'filter': 1}).then(response => {
      //   this.availableCountriesTableForm.availableCountriesList = response
      //   this.editAvailableCountriesDialog = true
      //   // this.multipleSelection = this.form.nature
      //   this.toggleSelection(this.form.nature)
      // }).catch(err => {
      //
      // })
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(item => { // checkedData为已选数据
          this.$nextTick( ()=>{
            this.availableCountriesTableForm.availableCountriesList.find(obj => { //  表单数据
              if(item.ID === obj.ID) {
                obj.sellPrice = item.sellPrice
                obj.marketPrice = item.marketPrice
                obj.taxRate = item.taxRate
                this.$refs.multipleTable.toggleRowSelection(obj)

              }
            })
          })
        })
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleRemove (file) {
      console.log(file)
    },
    upLoadSuccess (file) {
      this.form.cover = file
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
      this.file = file
      // console.log(file);
    },
    handleDownload (file) {
      console.log(file)
    },
    getFileToken () {
        getUploadToken().then(response => {
            this.uploadToken = response.data
        }).catch(err => {
            this.$message({
                message: this.$t('common.modifyData'),
                type: 'info'
            })
        })
    },
    getData (page, pageSize) {
      getAddGoodsConfig(this.filterModel).then(response => {
        this.categoryType = response.data.categoryType
        this.goodsType = response.data.goodsType
        this.GiftTypeArr = response.data.giftType
        this.sellType = response.data.sellType
        this.countries = response.data.countries
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    addSubmit () {
      this.submitButtonStat = true
      let path = 'shop/goods-add'
      let sen_gift = []
      this.form.giftType.map((item, index) => {
        if (item) {
          sen_gift.push((index + 1).toString())
        }
      })

      let postData = {
        goodsName: this.form.goodsName,
        sellDiscount: this.form.sellDiscount,
        discount: this.form.type.discount,
        type: this.form.type,
        giftType: sen_gift,
        // sellType: sellType,
        sellType: this.form.sellType,
        pvSplit: this.form.pvSplit,
        categoryType: this.form.categoryType,
        goodsNo: this.form.goodsNo,
        unit: this.form.unit,
        // marketPrice: this.form.marketPrice,
        // sellPrice: this.form.sellPrice,
        sellPriceStandard: this.form.sellPriceStandard,
        pricePv: this.form.pricePv,
        // point: this.form.point,
        storeNums: this.form.storeNums,
        content: this.form.content,
        sort: this.form.sort,
        cover: this.form.cover,
        // taxRate: this.form.taxRate
        nature: this.form.nature,
        autoMaintenance: this.form.autoMaintenance,
      }
      addGoods(postData).then(response => {
        this.$message({
          message: response.data,
          type: 'success'
        })
        this.submitButtonStat = false
        this.$router.go(-1)
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
        this.submitButtonStat = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/* 小于760 */
 @media (max-width:759px) {

    ::v-deep .el-input {
        width: 100% !important;
    }
   ::v-deep .el-input-number {
     width: 100% !important;
     .el-input {
       width: auto !important;
       padding: 0 5px;
     }
   }
   ::v-deep .el-input-number--medium {
     width: 100% !important;
   }
    ::v-deep .el-select {
        width: 100% !important;
    }

    ::v-deep .el-textarea {
        width: 100% !important;
    }
    ::v-deep .image-uploader {
        width: 100% !important;
    }
    ::v-deep i.el-icon-plus.uploader-icon {
        width:100% !important;
    }
    ::v-deep .form-page {
        width:100%;
        padding-left: 1%;
    }
    ::v-deep img {
        width: 100% !important;
        height: 100% !important;
    }
}

@media (min-width:760px) {
    ::v-deep .el-input {
        width: 400px !important;
    }
    ::v-deep .el-input-number {
      width: 100% !important;
      .el-input {
        width: auto !important;
        padding: 0 5px;
      }
    }
    ::v-deep .el-input-number--medium {
      width: 100% !important;
    }
    ::v-deep .el-select {
        width: 400px !important;
    }
    ::v-deep .el-textarea {
        width: 400px !important;
    }
    ::v-deep .upload-container {
        width: 400px !important;
    }
    ::v-deep .form-page {
        width:100%;
        padding-left: 10%;
    }
}

.el-input{
  width: 90%!important;
}
/* 去掉全选按钮 */
::v-deep .el-table .disabledCheck .cell .el-checkbox__inner {
  display: none !important;
}

::v-deep .el-table .disabledCheck .cell::before {
  content: '';
  text-align: center;
  line-height: 37px;
}

.left-aligned-input .el-input-number__inner {
  text-align: left;
}
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}

::v-deep .el-form-item{
  //margin-bottom: 16px !important;
  transform: translateY(6px);
}

</style>
