<template>
    <div v-loading="loading">
      <div class="white-box">
        <div class="filter-box">
            <filter-user :filter-types="filterTypes" @select-value="handleFilterUser"></filter-user>
        </div>
        <el-table class="table-box" ref="multipleTable" :data="tableData" stripe style="width: 100%;" :height="tool.getTableHeight()" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" v-if="tableHeaders" :selectable="checkSelectable"></el-table-column>
          <el-table-column v-for="(tableHeader, key) in tableHeaders" :key="key" :label="tableHeader.header" :width="tableHeader.other.width ? tableHeader.other.width : ''" :prop="tableHeader.other.prop ? tableHeader.other.prop : null">
            <template slot-scope="scope">
              <template v-if="scope.row[tableHeader.index].other.tag" >
                <el-tag :type="scope.row[tableHeader.index].other.tag.type ? scope.row[tableHeader.index].other.tag.type : null" :size="scope.row[tableHeader.index].other.tag.size ? scope.row[tableHeader.index].other.tag.size : null" :class="scope.row[tableHeader.index].other.tag.class ? scope.row[tableHeader.index].other.tag.class : null" >{{scope.row[tableHeader.index].value}}</el-tag>
              </template>
              <template v-else>
                <div v-html="scope.row[tableHeader.index].value"></div>
              </template>
            </template>
          </el-table-column>
          <el-table-column :fixed="fixedColumn" :label="$t('common.action')" width="180"><!-- 操作 -->
            <template slot-scope="scope">
              <el-dropdown size="small" trigger="click" v-if="permission.hasPermission(`shop/goods-edit`) || permission.hasPermission(`shop/goods-delete`)">
                <el-button type="primary" size="small" @click.stop="">
                  {{ $t('common.action') }}<!-- 操作该数据 --><i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="goods-edit" @click.native="handleEditShow(scope.row)">{{ $t('common.edit') }}<!-- 修改数据 --> </el-dropdown-item>
                  <el-dropdown-item command="del" @click.native="handleDel(scope.row.ID)" v-show="permission.hasPermission(`shop/goods-delete`)">
                    {{ $t('common.delete') }}<!-- 删除数据 -->
                  </el-dropdown-item>
                  <el-dropdown-item command="goods-edit" @click.native="handleGoodUp(scope.row.ID)">{{ $t('shop.onSale') }}<!-- 商品上架 --> </el-dropdown-item>
                  <el-dropdown-item command="goods-edit" @click.native="handleGoodDown(scope.row.ID)">{{ $t('shop.soldOut') }}<!-- 商品下架 --> </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
          <!--   <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="success" size="small" @click="handleGroupManage(scope.row)" >
                状态管理
              </el-button>
            </template></el-table-column>-->
        </el-table>
        <div class="white-box-footer">

         <!-- <el-dropdown size="small" trigger="click">
              <el-button type="primary" size="small">
                  所选数据<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="delete" @click.native="handleMuliDel()">上架</el-dropdown-item>
              </el-dropdown-menu>
          </el-dropdown>-->
          <el-button type="primary" size="small" @click="handlestate" icon="el-icon-plus" v-if="permission.hasPermission(`shop/goods-add`)">
            <!-- 商品添加 -->{{ $t('shop.addProduct') }}
          </el-button>

          <el-button type="success" size="small" @click="handleExport" v-show="permission.hasPermission(`shop/goods-list-export`)">{{ $t('common.exportExcel') }}</el-button>
          <!-- <el-button-group>
            <el-button type="success" size="mini" @click.native="handleup(scope.row.ID)">上架</el-button>
            <el-button type="danger" size="mini">下架</el-button>
          </el-button-group> -->
          <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange"></pagination>
        </div>
      </div>
      <el-dialog :title="$t('shop.editProducts')" :visible.sync="dialogEditFormVisible"><!-- 修改商品 -->
        <el-form :model="form"  v-loading="dialogEditLoading" label-width="130px" :label-position="labelPosition">
          <el-form-item :label="$t('shop.productName')"><!-- 商品名称 -->
            <el-input v-model="form.goodsName"></el-input>
          </el-form-item>
            <!-- <el-form-item label="商品来源">
              <el-select v-model="form.type">
                  <el-option v-for="(item,index) in goodsType" :key="index" :label="item.name"
                             :value="index"></el-option>
              </el-select>
            </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,index) in GiftTypeArr" v-model="value.checked" :key="index" >{{value.name}}</el-checkbox>
            </el-form-item>
            <!-- <el-form-item label="复消购买方式">
               <el-checkbox  v-for="(value,index) in sell_type" v-model="value.checked" :key="index" >{{value.name}}</el-checkbox>
            </el-form-item> -->
            <el-form-item :label="$t('shop.bvSplit')">
  <!--                      <el-checkbox v-model="form.pvSplit" :checked="form.pvSplit">Yes</el-checkbox>-->
              <el-select v-model="form.pvSplit" placeholder="">
                <el-option
                  v-for="item in pvSplitOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('shop.productCategory')"> <!-- 商品分类 -->
              <el-select v-model="form.categoryType">
                <el-option v-for="item in categoryType" :key="item.id" :label="item.name" :value="item.id" ></el-option>
              </el-select>
            </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.taxRate')">&lt;!&ndash; 税率 &ndash;&gt;-->
<!--              <el-input v-model="form.taxRate">-->
<!--                <template slot="append">%</template>-->
<!--              </el-input>-->
<!--            </el-form-item>-->
            <el-form-item :label="$t('shop.standardPrice')" p>
              <el-input v-model="form.sellPriceStandard" @input="sellPriceStandardInput"></el-input>
            </el-form-item>
<!--            <el-form-item :label="$t('shop.salesPrice')" p>-->
<!--              <el-input v-model="form.sellPrice"></el-input>-->
<!--            </el-form-item>-->
<!--            <el-form-item :label="$t('shop.marketPrice')">-->
<!--              <el-input v-model="form.marketPrice"></el-input>-->
<!--            </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="Exchange points" v-show="false"> &lt;!&ndash; 兑换积分 &ndash;&gt;-->
  <!--                        <el-input v-model="form.point"></el-input>-->
  <!--                    </el-form-item>-->
          <el-form-item :label="$t('shop.availableCountries')"><!-- 可购买国家 -->
            <el-button type="primary" size="small" @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
                  v-model="form.image"
                  :request-route="'v1/shop/upload'"
                  :default-image-url="form.cover"
                  width="100%"
                  height="260px"
                  @on-success="upLoadSuccess"
                ></Upload>
              </div>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogEditFormVisible = false">{{ $t('table.cancel') }}<!-- 取 消 --></el-button>
            <el-button type="primary" @click.native="handleEdit">{{ $t('table.edit') }}<!-- 修 改 --></el-button>
          </div>
      </el-dialog>

      <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" style="width: 90%" disabled></el-input>
          </el-form-item>
          <el-form-item :label="$t('transportationConfig.countryName')">
            <el-input
              v-model="searchQuery"
              placeholder=""
              style="width: 90%"
              @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="multipleTableCountries" @selection-change="countriesSelectionChange" @select="selectOne" :selectable="isRowSelectable" stripe :header-cell-class-name="cellClass" 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.01" :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" :min="0.01" :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 {getOperatingSystem, getScreenWidth} from "@/utils"
  import tool from '@/utils/tool'
  import baseInfo from '@/utils/baseInfo'
  import FilterUser from '@/components/FilterUser'
  import permission from '@/utils/permission'
  import Pagination from '@/components/Pagination'
  import filterHelper from '@/utils/filterHelper'
  import { shopList, goodsListExport, updateGoodsStatus, goodsDelete, getGoodsDetail, editGoodsData } from '@/api/shop'
  import Upload from '@/components/Upload'

  export default {
    name: 'index',
    components: {FilterUser, Pagination, Upload},
    mounted () {
      this.getData()
      // this.$refs.up_load.successImageUrl='';
      // let system =  getOperatingSystem()
      // if (system == "Android" || system == 'ios') {
      //   this.fixedColumn = false
      // } else {
      //   this.fixedColumn = 'right'
      // }
			this.fixedColumn = getScreenWidth() < 500 ? false : 'right'
    },

    data () {
      return {
        fixedColumn:false, // 固定,当手机端不固定,pc固定
        tableHeaders: null,
        tableData: null,
        loading: true,
        currentPage: 1,
        totalPages: 1,
        totalCount: 1,
        pageSize: 20,
        multipleSelection: [],
        tool: tool,
        permission: permission,
        baseDecLevels: baseInfo.decLevels(),
        baseEmpLevels: baseInfo.empLevels(),
        filterTypes: null,
        dialogVisible: false,
        dialogLoading: false,
        filterModel: {},
        value: [],
        selectedIds: '',
        dialogEditFormVisible: false,
        dialogEditLoading: false,
        pvSplitOptions: [
          {
            value: '0',
            label: this.$t('common.no')
          },
          {
            value: '1',
            label: this.$t('common.yes')
          }],
        form: {
          // sellType: [],
          goodsName: '',
          type: '',
          giftType: [],
          goodsNo: '',
          unit: '',
          marketPrice: '',
          sellPrice: '',
          sellPriceStandard: '',
          pricePv: '',
          point: '',
          storeNums: '',
          content: '',
          sort: '',
          discount: '',
          cover: '',
          textarea: '',
          sellDiscount: '',
          pvSplit: '',
          categoryType: '',
          sellType: 1,
          taxRate: 0,
          autoMaintenance: null,
        },
        submitButtonStat: false,
        goodsType: [],
        GiftTypeArr: [],
        sell_type: [],
        categoryType: [],
        img_show: true,
        pvDisabled: true,
        exchangeRate: baseInfo.exchangeRate(),
        labelPosition: getScreenWidth() >= 600 ? 'left' : 'top',
        editAvailableCountriesDialog: false,
        availableCountriesTableForm: {
          availableCountriesList: [],
          tempData:[],
        },
        multipleSelectionCountries: [],
          multipleSelectionTemp: [],

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

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

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

            }
            // const query = this.searchQuery.toLowerCase();
            that.$nextTick(() => {
                // 在数据更新后，重新设置选中的项
                console.log(this.searchQuery === "")
                console.log(query)

                if(!that.searchQuery){
                    console.log('no---')
                    that.setSelectionTemp();
                } else {
                    console.log('yes---')
                    that.availableCountriesTableForm.tempData = that.availableCountriesTableForm.availableCountriesList.filter(row => {
                        return row.NAME.toLowerCase().includes(query);
                    });
                    that.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.$refs.multipleTable.clearSelection();
            console.log('----00000')
            this.availableCountriesTableForm.tempData.forEach(row => {
                console.log('----1111')
                if (this.selectedIdsCountry.includes(row.ID)) {
                  this.$nextTick(() => {
                    this.$refs.multipleTableTemp.toggleRowSelection(row, true);
                  });
                }
            });
        },
        setSelectionTemp() {
            // this.$refs.multipleTable.clearSelection();
            let selectedIds = JSON.parse(JSON.stringify(this.selectedIdsCountry))
            let selectedIdsTemp = JSON.parse(JSON.stringify(this.selectedIdsTemp))

            console.log('----2222')
            let list = selectedIds.concat(selectedIdsTemp)
            console.log("list=====+" + list)
            this.availableCountriesTableForm.availableCountriesList.forEach(row => {
                console.log('----3333')
                if (list.includes(row.ID)) {
                    this.$refs.multipleTableCountries.toggleRowSelection(row, true);
                }
            });
        },
        handleRowClickTemp(row) {
            // 手动控制行点击时的选中状态
            // this.$refs.multipleTableTemp.toggleRowSelection(row,true);
        },
        handleSelectionChangeTemp(val) {
            this.multipleSelectionTemp = val;
            // 更新选中的项
            this.selectedIdsTemp = val.map(item => item.ID);
            this.updateRulesTemp();
        },
        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' }
                ];

            });
        },

        // 隐藏表头中的全选框
      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;
      },
      sellPriceStandardInput(value){
        console.log(value)
        // this.form.nature = []
        this.toggleSelection(this.form.nature, 'input')

      },
      countriesSelectionChange(val) {
        this.multipleSelectionCountries = val;
          this.selectedIdsCountry = val.map(item => item.ID);

        this.updateRules();
      },
      updateRules() {
        this.rules = {}; // 重置规则
        this.multipleSelectionCountries.forEach((row, index) => {
          this.rules[`availableCountriesList.${this.availableCountriesTableForm.availableCountriesList.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){
            console.log(row.CURRENCY_PRODUCT_RATE)
            // if(!row.CURRENCY_PRODUCT_RATE){
            //   return false
            // }
            row.sellPrice = (row.CURRENCY_PRODUCT_RATE * this.form.sellPriceStandard).toFixed(2)
            row.marketPrice = (row.sellPrice * 1.2).toFixed(2)
        },
      taxRateInput(scope){
        const value = parseFloat(scope.row.taxRate) || 0;
        if (value <= 0) {
          scope.row.taxRate = ''; // 更新输入框的值
        } else {
          let moment = this.availableCountriesTableForm.availableCountriesList[scope.$index]
          this.$set(this.availableCountriesTableForm.availableCountriesList,scope.$index, moment)
        }
      },
      marketPriceInput(scope){
        const value = parseFloat(scope.row.marketPrice) || 0;
        if (value <= 0) {
          scope.row.marketPrice = ''; // 更新输入框的值
        } else {
          let moment = this.availableCountriesTableForm.availableCountriesList[scope.$index]
          this.$set(this.availableCountriesTableForm.availableCountriesList,scope.$index, moment)
        }
      },
      submitAvailableCountries(){
        this.form.nature = this.multipleSelectionCountries
        this.editAvailableCountriesDialog = false
      },
      editAvailableCountries(){
        this.editAvailableCountriesDialog = true
        this.toggleSelection(this.form.nature,'data')

      },
      handleSelectionChange (val) {
        this.multipleSelection = val
      },
      handleCurrentChange (page) {
        this.getData(page, this.pageSize)
      },
      handleSizeChange (pageSize) {
        this.getData(this.currentPage, pageSize)
      },
      handleFilterUser (filterData) {
        filterHelper.handleFilterUser(this, filterData)
      },
      checkSelectable (row) {
        return row.DONT_DEL !== '1'
      },
      handleFilter () {
        this.getData()
      },
      handlestate () {
        this.$router.push({path: `/shop/goods-add`})
      },
      upLoadSuccess (file) {
        this.form.cover = tool.getArImage(file, '/files/')
        this.form.coverOrigin = file
        this.img_show = false
      },
      handleEditShow (row) {
        this.dialogEditLoading = true
        this.auditId = row.ID
        this.dialogEditFormVisible = true
        let vueObj = this
        getGoodsDetail({id: this.auditId}).then(response => {
            vueObj.dialogEditLoading = false
            vueObj.goodsType = response.data.goodsType
            vueObj.categoryType = response.data.categoryType
            let gift = response.data.goodsInfo.GIFT_TYPE;
            let gift_type = response.data.giftType
            let giftType = []
            if (gift.length > 0) {
                for (let i in gift_type) {
                    giftType.push({key: i, name: gift_type[i].name, checked: false})
                    gift.map((v, k) => {
                        if (v === i) {
                            giftType[i - 1].checked = true
                        }
                    })
                }
            }
            vueObj.GiftTypeArr = giftType
            vueObj.sell_type = response.data.goodsInfo.SELL_TYPE;
            vueObj.form.goodsName = response.data.goodsInfo.GOODS_NAME
            vueObj.form.sellDiscount = response.data.goodsInfo.SELL_DISCOUNT
            vueObj.form.goodsNo = response.data.goodsInfo.GOODS_NO
            vueObj.form.type = response.data.goodsInfo.TYPE
            vueObj.form.unit = response.data.goodsInfo.UNIT
            vueObj.form.marketPrice = response.data.goodsInfo.MARKET_PRICE
            vueObj.form.sellPrice = response.data.goodsInfo.SELL_PRICE
            vueObj.form.sellPriceStandard = response.data.goodsInfo.SELL_PRICE_STANDARD
            vueObj.form.pricePv = response.data.goodsInfo.PRICE_PV
            vueObj.form.point = response.data.goodsInfo.POINT
            vueObj.form.storeNums = response.data.goodsInfo.STORE_NUMS
            vueObj.form.content = response.data.goodsInfo.CONTENT
            vueObj.form.sort = response.data.goodsInfo.SORT
            vueObj.form.id = response.data.goodsInfo.ID
            vueObj.form.pvSplit = response.data.goodsInfo.PV_SPLIT
            vueObj.form.categoryType = parseInt(response.data.goodsInfo.CATEGORY_TYPE)
            vueObj.form.taxRate = response.data.goodsInfo.TAX_RATE
            vueObj.form.coverOrigin = response.data.goodsInfo.COVER
            vueObj.form.cover = tool.getArImage(response.data.goodsInfo.COVER, '/files/')
            vueObj.availableCountriesTableForm.availableCountriesList = response.data.goodsInfo.SHOP_GOODS_NATURE
            vueObj.form.autoMaintenance = response.data.goodsInfo.AUTO_MAINTENANCE
            const goods = JSON.parse(JSON.stringify(response.data.goodsInfo.SHOP_GOODS_NATURE))
            let nature = []
            goods.find(item => { //  表单数据
              if(item.SHOP_GOODS_NATURE.length > 0) {
                item.sellPrice = item.SHOP_GOODS_NATURE[0].SELL_PRICE
                item.taxRate = item.SHOP_GOODS_NATURE[0].TAX_RATE
                item.marketPrice = item.SHOP_GOODS_NATURE[0].MARKET_PRICE
                nature.push(item)
              }
              vueObj.form.nature = JSON.parse(JSON.stringify(nature))
            })
            console.log(vueObj.form.nature)

            this.$forceUpdate()
        }).catch(err => {

        })
      },
      toggleSelection(rows, type) {
        let data = JSON.parse(JSON.stringify(rows))
        if(data.length > 0 && type === 'input'){
          let checkedData = this.form.nature
          checkedData.forEach(item => { // checkedData为已选数据
            this.$nextTick( ()=>{
              this.availableCountriesTableForm.availableCountriesList.find(obj => { //  表单数据
                if(item.ID === obj.ID) {
                  obj.sellPrice = (item.CURRENCY_PRODUCT_RATE * this.form.sellPriceStandard).toFixed(2)
                  obj.taxRate = item.taxRate
                  obj.marketPrice = (obj.sellPrice * 1.2).toFixed(2)
                  this.$refs.multipleTableCountries.toggleRowSelection(obj,true)
                }
              })
            })
          })
          return false
        }
        else if (data.length > 0 && type === 'data') {
          data.forEach(item => { // checkedData为已选数据
            this.$nextTick( ()=>{
              this.availableCountriesTableForm.availableCountriesList.find(obj => { //  表单数据
                if(item.ID === obj.ID) {
                  obj.sellPrice = item.sellPrice
                  obj.taxRate = item.taxRate
                  obj.marketPrice = item.marketPrice
                  this.$refs.multipleTableCountries.toggleRowSelection(obj,true)
                }
              })
            })
          })
        } else {
          this.$refs.multipleTableCountries.clearSelection();
        }
      },
      handleEdit () {
        this.dialogEditFormVisible = false
        this.$message({
          message: this.$t('common.modifyData'), // 正在修改数据
          type: 'info'
        })
        // let sen_sell=[];
        // this.sell_type.map((item,index)=>{
        //     if(item.checked){
        //         sen_sell.push(item.key);
        //     }
        // })
        // this.form.sellType=sen_sell;

        let sen_gift = []
        this.GiftTypeArr.map((item, index) => {
          if (item.checked) {
            sen_gift.push(item.key)
          }
        })
        this.form.giftType = sen_gift
        this.form.sellType = 1
        this.form.cover = this.form.coverOrigin
        delete this.form.coverOrigin
        editGoodsData({...this.form}).then(response => {
          this.$message({
            message: response.data,
            type: 'success'
          })
          this.getData(this.currentPage, this.pageSize)
        }).catch(err => {
          this.$message({
            message:err,
            type: 'error'
          })
        })
      },

      handleDel (id = null) {
        let obj = this
        this.$confirm(this.$t('common.deleteTips'), this.$t('common.hint'), { // '确定删除选定的数据？', '提示'
          confirmButtonText: this.$t('common.confirm'), // 确定
          cancelButtonText: this.$t('common.cancel'), // 取消
          type: 'warning'
        }).then(() => {
          let selectedIds = []
          if (id === null) {
            for (let val of obj.multipleSelection) {
              selectedIds.push(val.ID)
            }
          } else {
            selectedIds.push(id)
          }
          goodsDelete({selected: selectedIds}).then(response => {
            this.$message({
                message: response.data,
                type: 'success'
            })
            obj.getData(obj.currentPage, obj.pageSize)
          }).catch(err => {
            this.$message({
                message: err,
                type: 'error'
            })
          })
        })
      },
      getData (page, pageSize) {
        let filterData = this.filterModel
        /* this.allData = response */
        let vueObj=this
        const paramsData = Object.assign({
        page: (page === null || page == undefined) ? 1 : page,
        pageSize: (pageSize === null || pageSize == undefined) ? vueObj.pageSize : pageSize
        }, filterData)
        shopList(paramsData).then(response => {
            vueObj.tableHeaders = response.data.columnsShow ? response.data.columnsShow : []
            vueObj.tableData = response.data.list
            vueObj.filterTypes = response.data.filterTypes
            vueObj.currentPage = page
            vueObj.totalPages = parseInt(response.data.totalPages)
            vueObj.totalCount = parseInt(response.data.totalCount)
            vueObj.pageSize = pageSize
            this.loading = false
        }).catch(err => {
            this.loading = false
            this.$message({
                message: err,
                type: 'error'
            })
        })
      },
      handleGoodUp (id) {
        updateGoodsStatus({selectedIds: id, status: 1}).then(response => {
            this.$message({
              message: response.data,
              type: 'success'
            })
            this.getData(this.currentPage, this.pageSize)
        }).catch(err => {
            this.$message({
              message: err,
              type: 'error'
            })
        })
      },
      handleGoodDown (id) {
        updateGoodsStatus({selectedIds: id, status: 0}).then(response => {
            this.$message({
              message: response.data,
              type: 'success'
            })
            this.getData(this.currentPage, this.pageSize)
        }).catch(err => {
            this.$message({
              message: err,
              type: 'error'
            })
        })
      },

      handleExport () {
        this.$confirm(this.$t('financial.exportNotice'), this.$t('common.hint'), { // 确定要导出当前数据吗？`, '提示'
          confirmButtonText: this.$t('common.confirm'), // 确定
          cancelButtonText: this.$t('common.cancel'), // 取消
          type: 'warning'
        }).then(() => {
            goodsListExport(this.filterModel).then(response => {
                this.$message({
                    message: response.data,
                    type: 'success'
                })
            }).catch(err => {
                this.$message({
                    message: err,
                    type: 'error'
                })
            })
        })
      },
    },
    watch: {
      // 监听商品分类,控制PV是否展示
      'form.categoryType': {
        deep: true,
        handler (modern, origin) {
          this.pvDisabled = (parseInt(modern) === 1)
        }
      },
      // 监听商品标准价格,自动计算销售价格
      // 'form.sellPriceStandard': {
      //     deep: true,
      //     handler(modern, origin) {
      //
      //     }
      // },
    }
  }

  </script>

  <style scoped>
      .table-box .el-form-item__label {
          width: 100px;
          color: #99a9bf;
      }

      .table-box .el-form-item {
          width: 30%;
          margin-right: 0;
          margin-bottom: 0;
      }
      /* /deep/ .el-dialog .el-form-item__label {
        width:100%;
        text-align: left;
      } */
      /deep/ img {
        width: 100% !important;
        height: 100% !important;
      }

      @media (max-width:862px) {
        /deep/ .el-dialog {
          width:100%;
        }
      }
      ::v-deep .el-input-number {
        width: 100% !important;
        .el-input {
          width: auto !important;
          padding: 0 5px;
        }
      }

      ::v-deep .el-input-number .el-input__inner {
        text-align: left;
      }
      ::v-deep .el-form-item{
        transform: translateY(6px);
      }
      /* 去掉全选按钮 */
      ::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;
      }
  </style>
