<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">{{ $t('cuxiao.home') }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $t('cuxiao.yuiquangl') }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $t('quanyi.kyyhq') }}</el-breadcrumb-item>
    </el-breadcrumb>
    <div style="margin-top: 30px;display: flex;align-items: center;">
      <el-button v-for="item in storeList" :type="dqmd==item.id?'primary':'info'" class="biaoqian" @click="xuanzhemd(item.id)">{{item.posName}}</el-button>
    </div>
    <el-row :gutter="10" style="margin-top: 20px;margin-bottom: 20px;">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >{{ $t('quanyi.add') }}
        </el-button>
      </el-col>
    </el-row>
    <el-table ref="filterTable" v-loading="loding" :data="tableData" :header-cell-style="{background:'#f0f0f0'}">
      <el-table-column
          prop="id"
          label="id"
      >
      </el-table-column>
      <el-table-column
          prop="name"
          :label="$t('quanyi.yhmc')"
      >
      </el-table-column>
      <el-table-column
          prop="yhfangs"
          :label="$t('quanyi.yhfs')"
          width="200"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.yhfangs== '1'">{{ $t('quanyi.yhqlx1') }}</span>
          <span v-else-if="scope.row.yhfangs == '2'">{{ $t('quanyi.yhqlx2') }}</span>
          <span v-else-if="scope.row.yhfangs == '3'">{{ $t('quanyi.yhqlx3') }}</span>
<!--          <span v-else-if="scope.row.yhfangs == '3'">{{ $t('quanyi.yhqlx4') }}</span>-->
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="total"
          :label="$t('quanyi.total')"
      >
      </el-table-column>
      <el-table-column
          prop="claimedCount"
          :label="$t('quanyi.claimedCount')"
      >
      </el-table-column>

      <el-table-column
          prop="createTime"
          :label="$t('quanyi.creatTime')"
          width="200"
      >
      </el-table-column>
      <el-table-column
          prop="state"
          :label="$t('quanyi.zt')"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.state == '0'">{{ $t('quanyi.qy') }}</span>
          <span v-else-if="scope.row.state == '1'">{{ $t('quanyi.gb') }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          :label="$t('mendian.operate')"
          width="120">
        <template slot-scope="scope">
          <el-button @click="handleUpdate(scope.row)" type="text" size="small">{{ $t('cuxiao.modify') }}</el-button>
          <el-button @click="delechansu(scope.row)" type="text" size="small">{{ $t('cuxiao.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="width: 100%;display: flex;justify-content: flex-end;">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.page"
          :page-size="queryParams.size"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="text" :visible.sync="open"
               :width="$t('loding.language')=='en'||$t('loding.language')=='vi'?'650px':'600px'" append-to-body>
      <el-alert
          v-if="!form.edit"
          :title="$t('quanyi.bnxg')"
          type="error"
          show-icon
          :closable="false"
          style="margin-bottom: 16px;"
      />
      <el-form ref="form" :model="form" :rules="rules"
               :label-width="$t('loding.language')=='en'||$t('loding.language')=='vi'?'180px':'100px'">
          <el-form-item :label="$t('quanyi.md')">
            <el-select :disabled="!form.edit" v-model="form.shId" :placeholder="$t('quanyi.xcmd')" style="width: 180px;" @change="handleStoreChange">
              <el-option v-for="item in storeList" :key="item.id" :label="item.posName" :value="item.id" />
            </el-select>
          </el-form-item>
        <el-form-item :label="$t('quanyi.yhmc')" prop="name">
          <el-input v-model="form.name" :placeholder="$t('quanyi.sryhmc')" :readonly="!form.edit"/>
        </el-form-item>
<!--        <el-form-item :label="$t('cuxiao.hdhb')" prop="poster">-->
<!--          <el-upload-->
<!--              class="avatar-uploader"-->
<!--              :action="seruer+'/utils/Upload'"-->
<!--              :show-file-list="false"-->
<!--              :on-success="handleAvatarlogo"-->
<!--              :before-upload="beforeAvatarUpload">-->
<!--            <img v-if="form.poster" :src="seruer+form.poster" class="avatar">-->
<!--            <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
        <el-form-item :label="$t('quanyi.yhfs')" prop="yhfangs" >
          <el-radio :disabled="!form.edit" v-model="form.yhfangs" :label="1">{{ $t('quanyi.yhqlx1') }}</el-radio>
          <el-radio :disabled="!form.edit" v-model="form.yhfangs" :label="2">{{ $t('quanyi.yhqlx2') }}</el-radio>
          <el-radio :disabled="!form.edit" v-model="form.yhfangs" :label="3">{{ $t('quanyi.yhqlx3') }}</el-radio>
<!--          <el-radio v-model="form.yhfangs" :label="3">{{ $t('quanyi.yhqlx4') }}</el-radio>-->
        </el-form-item>
<!--        <el-form-item v-if="form.yhfangs == '3'" :label="$t('quanyi.xcsp')" prop="spId">-->
<!--          <div style="display: flex; align-items: center;">-->
<!--            <el-button type="primary" @click="openSelectProductDialog">{{$t('quanyi.xcsp')}}</el-button>-->
<!--            <div v-if="selectedProduct && selectedProduct.name" style="margin-left: 16px;display: flex;align-items: center;">-->
<!--              <img v-if="selectedProduct.image" :src="seruer+selectedProduct.image" style="width:40px;height:40px;margin-right:8px;" />-->
<!--              <span>{{selectedProduct.name}}</span>-->
<!--            </div>-->
<!--          </div>-->
<!--        </el-form-item>-->
        <el-form-item :label="$t('quanyi.yhnum')" prop="yhnum">
          <el-input type="number" v-model="form.yhnum" :placeholder="$t('quanyi.sryhnum')" :readonly="!form.edit"/>
        </el-form-item>
        <el-form-item :label="$t('quanyi.total')" prop="total">
          <el-input type="number" v-model="form.total" :placeholder="$t('quanyi.srtotal')" :readonly="!form.edit"/>
        </el-form-item>
        <el-form-item :label="$t('quanyi.lqxz')" prop="lqxz">
          <el-input type="number" v-model="form.lqxz" :placeholder="$t('quanyi.srlqxz')" :readonly="!form.edit"/>
        </el-form-item>
        <el-form-item :label="$t('quanyi.validity')" prop="validity">
          <el-input type="number" v-model="form.validity"  min="1" :placeholder="$t('quanyi.srvalidity')" :readonly="!form.edit"/>
        </el-form-item>

        <el-form-item :label="$t('quanyi.tiaojian')" prop="tiaojian">
          <el-input type="number" v-model="form.tiaojian" :placeholder="$t('quanyi.srtiaojian')" :readonly="!form.edit"/>
        </el-form-item>
        <el-form-item :label="$t('quanyi.zt')" prop="state">
          <el-radio v-model="form.state" label="0">{{ $t('quanyi.qy') }}</el-radio>
          <el-radio v-model="form.state" label="1">{{ $t('quanyi.gb') }}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('quanyi.shuoming')" prop="shuoming">
          <el-input type="textarea" v-model="form.shuoming" :placeholder="$t('quanyi.srshuoming')"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="tijiaobaocun">{{ $t('mendian.determine') }}</el-button>
        <el-button @click="cancel">{{ $t('mendian.cancellation') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="$t('quanyi.xcsp')" :visible.sync="selectProductDialogVisible" width="800px">
      <div style="margin-bottom: 12px;">
        <el-form inline>
<!--          <el-form-item :label="$t('quanyi.md')">-->
<!--            <el-select v-model="selectedStoreId" :placeholder="$t('quanyi.xcmd')" style="width: 180px;" @change="handleStoreChange">-->
<!--              <el-option v-for="item in storeList" :key="item.id" :label="item.posName" :value="item.id" />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item :label="$t('quanyi.spfl')">
            <el-select v-model="selectedProductCategory" :placeholder="$t('quanyi.spfl')" style="width: 180px;" @change="handleCategoryChange">
              <el-option v-for="item in productCategoryList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('quanyi.spmc')">
            <el-input v-model="productTableQuery.name" :placeholder="$t('quanyi.spmc')" style="width: 180px;" @keyup.enter.native="getProductTableData" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="getProductTableData">{{$t('quanyi.cx')}}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="productTableData" highlight-current-row @current-change="handleProductTableSelect" :row-key="row=>row.id" style="width:100%;">
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="name" :label="$t('quanyi.spmc')" />
        <el-table-column prop="image" :label="$t('quanyi.tp')" width="80">
          <template slot-scope="scope">
            <img v-if="scope.row.image" :src="seruer+scope.row.image" style="width:40px;height:40px;" />
          </template>
        </el-table-column>
        <el-table-column prop="price" :label="$t('quanyi.jg')" />
      </el-table>
      <div style="margin-top: 10px;text-align: right;">
        <el-pagination
          @size-change="handleProductTableSizeChange"
          @current-change="handleProductTableCurrentChange"
          :current-page="productTableQuery.page"
          :page-size="productTableQuery.size"
          layout="total, prev, pager, next"
          :total="productTableTotal">
        </el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="selectProductDialogVisible=false">{{$t('quanyi.qx')}}</el-button>
        <el-button type="primary" @click="handleProductSelectConfirm">{{$t('quanyi.qd')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {listQuanyi,getQuanyi,addQuanyi,updateQuanyi,delQuanyi} from '@/api/quanyi';
import googmap from "@/components/googmap.vue";
import { storelistlist, getordfenlei,getFoodPageList,getFood } from '@/api/food';
import Bus from "@/utils/Bus"; // 路径按你实际情况

export default {
  name: "AcidrollingCapacity",
  components: {
    googmap
  },
  data() {
    return {
      seruer: process.env.VUE_APP_BASE_URL ,
      loding: false,
      tableData: [],
      total: 0,
      checkList: [],
      //分页
      queryParams: {
        page: 1,
        size: 10,
        language:this.$t('loding.lass')
      },
      fenlei: [],
      fwlxlist: [],
      open: false,
      opmap: false,
      form: {edit:true},
      user: {},
      mdid: '',
      // 表单校验
      rules: {
        name: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error(this.$t('quanyi.nameEpty')));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        yhfangs: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value && value !== 0) {
                callback(new Error(this.$t('quanyi.yhfangsEmpty')));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        yhnum: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value && value !== 0) {
                callback(new Error(this.$t('quanyi.yhnumEmty')));
              } else if (this.form.yhfangs != 1 && value <= 0) {
                callback(new Error(this.$t('quanyi.yhmnum0')));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        total: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value && value !== 0) {
                callback(new Error(this.$t('quanyi.totalEmty')));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        lqxz: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value && value !== 0) {
                callback(new Error(this.$t('quanyi.lqxzEmty')));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        validity:[
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value && value !== 0) {
                callback(new Error(this.$t('quanyi.validityEmty')));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        state:[
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value && value !== 0) {
                callback(new Error(this.$t('quanyi.stateEmty')));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        spId: [
          {
            validator: (rule, value, callback) => {
              if (this.form.yhfangs == '3' && !value) {
                callback(new Error(this.$t('quanyi.qxcsp')));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      },
      mapaddress: null,
      text: '',
      productList: [],
      selectProductDialogVisible: false,
      productTableData: [],
      productTableTotal: 0,
      productTableQuery: { page: 1, size: 8, name: '', type: '' },
      selectedProduct: {},

      storeList: [], // 门店列表
      selectedStoreId: '', // 当前选中的门店ID
      productCategoryList: [], // 分类列表
      selectedProductCategory: '', // 当前选中的分类ID
      language:this.$t('loding.lass'),
      dqmd:null,
    }
  },
  created() {
    this.getStoreList();
    const that = this;
    Bus.$on('l18zh',function(res){
      that.language = res;
    })
  },
  watch: {
    language(newVal) {
      // 语言变化时执行逻辑
      this.listQuanyi();
    }
  },
  methods: {
    xuanzhemd(id){
      this.dqmd = id;
      this.listQuanyi()
    },
    delechansu(e) {
      this.$confirm(this.$t('cuxiao.delSm'), this.$t('mendian.prompt'), {
        confirmButtonText: this.$t('mendian.determine'),
        cancelButtonText: this.$t('mendian.cancellation'),
        type: 'warning'
      }).then(() => {
        delQuanyi(e.id).then(res => {
          // console.log('删除',res);
          if (res.code == 200) {
            this.listQuanyi();
            this.$message({
              type: 'success',
              message: this.$t('mendian.successful')
            });
          } else {
            this.$message({
              type: 'info',
              message: this.$t('mendian.Deletefailed')
            });
          }

        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('mendian.undelete')
        });
      });

    },
    tijiaobaocun() {
      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateQuanyi(this.form).then(res => {
              // console.log('操作成功',res)
              if (res.code == 200) {
                this.listQuanyi();
                this.open = false;
                this.reset();
              }
            })
          } else {
            this.form.language=this.language=='zh'?'2':this.language=='tw'?'3':this.language=='en'?'1':'0';
            addQuanyi(this.form).then(res => {
              // console.log('操作成功',res)
              if (res.code == 200) {
                this.listQuanyi();
                this.open = false;
                this.reset();
              }
            })
          }

        }
      });

    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getQuanyi(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.text = this.$t('cuxiao.modify');
        // 关键：如果是减免个别商品，并且有 spId，查商品详情
        if(this.form.yhfangs == '3' && this.form.spId) {
          getFood(this.form.spId).then(f => {
            this.selectedProduct = {
              id: f.data.id,
              name: f.data.name,
              image: f.data.image
            };
          });
        } else {
          this.selectedProduct = {};
        }
      });
    },
    reset() {
      this.form = {
        id: null,
        vip: null,
        yhfangs: null,
        yhnum: null,
        name: null,
        shuoming: null,
        tiaojian: null,
        num: null,
        state: null,
        total: null,
        validity: null,
        lqxz: null,
        shId:null,
        spId: null,
        poster:null,
        language:null,
        edit:true
      };
      this.selectedProduct = {};
    },
    handleAdd() {
      this.reset();
      this.text = this.$t('quanyi.add');
      this.open = true;
      this.form.shId=this.dqmd;
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    listQuanyi() {
      var that = this;
      that.loding = true;
      this.queryParams.language= this.language=='zh'?'2':this.language=='tw'?'3':this.language=='en'?'1':'0';
      this.queryParams.shId= this.dqmd;
      listQuanyi(this.queryParams).then(response => {
        that.loding = false;
        this.total = response.data.total;
        this.tableData = response.data.records;
      });
    },

    //翻页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.queryParams.size = val;
      this.listQuanyi();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.queryParams.page = val;
      this.listQuanyi();
    },
    handleAvatarlogo(res, file) {
      // this.upimg = URL.createObjectURL(file.raw);
      this.form.poster = file.response.data;
      // console.log('上传图片',file.response);

    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error(this.$t('quanyi.ItcanonlyJPG'));
      }
      if (!isLt2M) {
        this.$message.error(this.$t('quanyi.Cannotexceed'));
      }
      return isJPG && isLt2M;
    },

    openSelectProductDialog() {
      this.selectProductDialogVisible = true;

    },
    getStoreList() {
      storelistlist().then(res => {
        if (res.data && res.data.records && res.data.records.length > 0) {
          this.storeList = res.data.records;
          this.selectedStoreId = res.data.records[0].id;
          this.dqmd=res.data.records[0].id;
          this.listQuanyi()
          this.getProductCategoryList(); // 获取第一个门店的分类
        }
      });
    },
    getProductCategoryList() {
      if (!this.selectedStoreId) {
        this.productCategoryList = [];
        this.selectedProductCategory = '';
        return;
      }
      const language =this.language=='zh'?'2':this.language=='tw'?'3':this.language=='en'?'1':'0';
      getordfenlei(this.selectedStoreId, language).then(res => {
        if (res.data && res.data.length > 0) {
          this.productCategoryList = res.data;
          this.selectedProductCategory = res.data[0].id;
          this.getProductTableData();
        } else {
          this.productCategoryList = [];
          this.selectedProductCategory = '';
          this.productTableData = [];
        }
      });
    },
    handleProductTableCurrentChange(val) {
      this.productTableQuery.page = val;
      this.getProductTableData();
    },
    handleProductTableSizeChange(val) {
      this.productTableQuery.size = val;
      this.getProductTableData();
    },
    handleProductTableSelect(row) {
      this.selectedProduct = row;
    },
    handleProductSelectConfirm() {
      if(this.selectedProduct) {
        this.form.spId = this.selectedProduct.id;
        this.selectProductDialogVisible = false;
      } else {
        this.$message.warning('请选择商品');
      }
    },
    // 门店切换
    handleStoreChange() {
      this.selectedStoreId =this.form.shId
      this.getProductCategoryList();
    },
    // 分类切换
    handleCategoryChange() {
      this.getProductTableData();
    },
    // 获取商品列表
    getProductTableData() {
      const lang = this.$t('loding.language')=='zh'?'2':this.$t('loding.language')=='tw'?'3':this.$t('loding.language')=='en'?'1':'0';
      const params = {
        page: this.productTableQuery.page,
        size: this.productTableQuery.size,
        name: this.productTableQuery.name,
        lang: lang,
        flId: this.selectedProductCategory,
        mdId: this.selectedStoreId // 如果接口需要门店id
      };
      getFoodPageList(params).then(res => {
        if(res.data && res.data.records) {
          this.productTableData = res.data.records || [];
          this.productTableTotal = res.data.total || 0;
        }
      });
    },
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
