<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form label-width="77px" class="ele-form-search">
        <el-row :gutter="15">
          <el-col :md="6" :sm="12">
            <el-form-item label="名称:">
              <el-input
                placeholder="请输入名称"
                clearable
                v-model="where.title"
              />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="12">
            <el-form-item label="上架状态:">
              <el-select v-model="where.status" clearable>
                <el-option value="1" label="上架" />
                <el-option value="0" label="未上架" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="12">
            <car-model-selector
              type="brandSeries"
              v-model="where.selectedCar"
              :key="componentKey"
            />
          </el-col>
          <!--
          <el-col :md="12" :sm="12">
            <el-form-item label="补贴金额:">
              <el-input
                v-model="where.minPrice"
                placeholder="最小金额"
                style="width: 45%"
              >
                <template #append>~</template>
              </el-input>
              <el-input
                v-model="where.maxPrice"
                placeholder="最大金额"
                style="width: 45%"
              ></el-input>
            </el-form-item>
          </el-col>
          -->
          <el-col :md="6" :sm="12">
            <el-form-item label="推广范围:">
              <regions-select
                v-model="where.citys"
                type="provinceCity"
                placeholder="请选择省市"
                :props="{ multiple: true }"
                class="ele-fluid"
              />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="12">
            <el-form-item label="价格区间:">
              <el-select v-model="where.priceRange" multiple>
                <el-option
                  v-for="item in priceRange"
                  :key="item.dictDataId"
                  :value="item.dictDataId"
                  :label="item.dictDataName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="12">
            <el-form-item label="能源类型:">
              <el-select v-model="where.carProductLabel" multiple>
                <el-option
                  v-for="item in carProductLabel"
                  :key="item.dictDataId"
                  :value="item.dictDataId"
                  :label="item.dictDataName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="12">
            <el-form-item label="车辆级别:">
              <el-select v-model="where.productLevel" multiple>
                <el-option
                  v-for="item in productLevel"
                  :key="item.dictDataId"
                  :value="item.dictDataId"
                  :label="item.dictDataName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="12">
            <el-form-item label="上架时间:">
              <el-date-picker
                unlink-panels
                v-model="where.dateRange"
                range-separator="-"
                type="daterange"
                end-placeholder="结束日期"
                start-placeholder="开始日期"
                value-format="yyyy-MM-dd"
                class="ele-fluid"
              />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="12">
            <div class="ele-form-actions">
              <el-button
                type="primary"
                icon="el-icon-search"
                class="ele-btn-icon"
                @click="reload"
              >
                查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :selection.sync="selection"
        cache-key="syliveActivityTable"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="dropClick('edit')"
          >
            新建
          </el-button>
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            class="ele-btn-icon"
            @click="removeBatch"
          >
            删除
          </el-button>
        </template>
        <template v-slot:cityName="{ row }">
          {{ row.cityName[0] }}
          <el-link
            size="mini"
            v-if="row.cityName.length > 1"
            type="primary"
            class="ele-btn-icon"
            @click="showAllCityName(row)"
          >
            查看所有>>
          </el-link>
        </template>
        <!-- 状态列 -->
        <template v-slot:title="{ row }">
          <div class="ele-cell-content">
            <el-image
              v-if="row.banner[0] && row.banner[0]['url']"
              :src="row.banner[0]['url']"
              class="table-image"
            />
          </div>
          <div>
            <el-link
              type="primary"
              :underline="false"
              class="table-text"
              style="width: 100%"
              @click="showEditRow(row)"
            >
              <div>{{ row.title }}</div>
              <div>{{ row.guide_price }}</div>
              <div>
                <template v-for="item in priceRange">
                  <el-tag
                    :key="item.dictDataId"
                    v-if="row.labels.includes(item.dictDataId)"
                    size="mini"
                    >{{ item.dictDataName }}</el-tag
                  >
                </template>
                <template v-for="item in productLevel">
                  <el-tag
                    :key="item.dictDataId"
                    v-if="row.labels.includes(item.dictDataId)"
                    size="mini"
                    >{{ item.dictDataName }}</el-tag
                  >
                </template>
                <template v-for="item in carProductLabel">
                  <el-tag
                    :key="item.dictDataId"
                    v-if="row.labels.includes(item.dictDataId)"
                    size="mini"
                    >{{ item.dictDataName }}</el-tag
                  >
                </template>
              </div>
            </el-link>
          </div>
          <!--
          <div class="cell-content">
            <el-image
              v-if="row.banner && row.banner[0]"
              :src="row.banner[0]['url']"
              class="table-image"
            />
            <span class="table-text">{{ row.title }}</span>
          </div>
          -->
        </template>
        <template v-slot:status="{ row }">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="row.status"
            @change="editStatus(row)"
          />
        </template>
        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-dropdown @command="(command) => dropClick(command, row)">
            <el-link type="primary" :underline="false" icon="el-icon-edit">
              修改
              <i class="el-icon-arrow-down"></i>
            </el-link>
            <template v-slot:dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="editCps">CPS</el-dropdown-item>
                <el-dropdown-item command="edit">产品</el-dropdown-item>
                <el-dropdown-item command="brokerage">佣金</el-dropdown-item>
                <el-dropdown-item command="coupon">优惠券</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-popconfirm
            class="ele-action"
            title="确定要删除此数据吗？"
            @confirm="remove(row)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>
    <!-- 编辑弹窗 -->
    <edit :data="current" :visible.sync="showEdit" @done="reload" />
    <edit-brokerage
      :data="current"
      :visible.sync="showEditBrokerage"
      @done="reload"
    />
    <!-- 修改CPS-->
    <edit-cps :data="current" :visible.sync="showEditCps" @done="reload" />
    <ele-modal
      width="800px"
      :visible.sync="showCityName"
      :append-to-body="true"
      :close-on-click-modal="true"
      custom-class="ele-dialog-form"
      title="推广范围"
    >
      <el-row style="padding-bottom: 20px">
        <template v-for="(item, index) in cityNames">
          <el-tag :key="index" type="info" style="margin-bottom: 10px">{{
            item
          }}</el-tag>
        </template>
      </el-row>
    </ele-modal>
  </div>
</template>

<script>
  import { listDictionaryData } from '@/api/system/dictionary-data';
  import {
    pageProduct,
    removeProduct,
    updateProductStatus
  } from '@/api/car/product';
  import edit from './components/edit.vue';
  import editBrokerage from './components/editBrokerage.vue';
  import CarModelSelector from '@/components/CarSelector/index.vue';
  import RegionsSelect from '@/components/RegionsSelect/index.vue';
  import editCps from './components/editCps.vue';

  export default {
    name: 'carProduct',
    components: {
      RegionsSelect,
      CarModelSelector,
      edit,
      editBrokerage,
      editCps
    },
    data() {
      return {
        where: {
          title: '',
          selectedCar: {
            brandId: '',
            seriesId: '',
            modelId: ''
          },
          status: '',
          dateRange: '',
          minPrice: '',
          maxPrice: '',
          priceRange: [],
          carProductLabel: [],
          productLevel: []
        },
        // 表格列配置
        columns: [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'id',
            label: 'ID',
            minWidth: 40,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'title',
            label: '产品信息',
            slot: 'title',
            align: 'center',
            width: 200,
            fixed: 'left'
          },
          {
            prop: 'cityName',
            label: '推广范围',
            showOverflowTooltip: true,
            minWidth: 80,
            slot: 'cityName',
            align: 'center'
          },
          {
            prop: 'timeLaunch',
            label: '上架时间',
            sortable: 'custom',
            showOverflowTooltip: true,
            minWidth: 100,
            align: 'center'
          },
          {
            prop: 'status',
            label: '上架状态',
            align: 'center',
            width: 80,
            resizable: false,
            slot: 'status',
            showOverflowTooltip: true
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 200,
            align: 'center',
            resizable: false,
            slot: 'action'
          }
        ],
        // 表格选中数据
        selection: [],
        // 当前编辑数据
        current: null,
        // 是否显示编辑弹窗
        showEdit: false,
        componentKey: 0,
        // 佣金编辑框
        showEditBrokerage: false,
        showCityName: false,
        cityNames: [],
        //价格区间
        priceRange: [],
        //能源类型
        productLevel: [],
        //产品标签
        carProductLabel: [],
        //用户画像
        crowdProfiling: [],
        couponSelling: [],
        showBizList: false,
        bizList: [],
        //是否显示修改CPS
        showEditCps: false
      };
    },
    created() {
      listDictionaryData({ dictCode: 'priceRange' }).then((data) => {
        this.priceRange = data;
      });
      listDictionaryData({ dictCode: 'productLevel' }).then((data) => {
        this.productLevel = data;
      });
      listDictionaryData({ dictCode: 'carProductLabel' }).then((data) => {
        this.carProductLabel = data;
      });
      listDictionaryData({ dictCode: 'crowdProfiling' }).then((data) => {
        this.crowdProfiling = data;
      });
      listDictionaryData({ dictCode: 'couponSelling' }).then((data) => {
        this.couponSelling = data;
      });
    },
    methods: {
      /* 下拉按钮点击 */
      dropClick(command, row) {
        if (command === 'edit') {
          this.showEditRow(row);
        } else if (command === 'brokerage') {
          this.current = row;
          this.showEditBrokerage = true;
        } else if (command === 'coupon') {
          const path = '/car/product/coupon';
          this.$nextTick(() => {
            this.$router.push({
              path,
              query: row ? { id: row.id, title: row.title } : undefined
            });
          });
        } else if (command === 'editCps') {
          this.current = row;
          this.showEditCps = true;
        }
      },
      showEditRow(row) {
        this.current = row;
        this.showEdit = true;
      },
      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        return pageProduct({ ...where, ...order, page, limit });
      },
      /* 刷新表格 */
      reload() {
        this.$refs.table.reload({
          page: this.$refs.table.page,
          where: this.where
        });
      },
      /* 删除 */
      remove(row) {
        const loading = this.$loading({ lock: true });
        removeProduct(row.id)
          .then((msg) => {
            loading.close();
            this.$message.success(msg);
            this.reload();
          })
          .catch((e) => {
            loading.close();
            this.$message.error(e.message);
          });
      },
      /* 批量删除 */
      removeBatch() {
        if (!this.selection.length) {
          this.$message.error('请至少选择一条数据');
          return;
        }
        this.$confirm('确定要删除选中数据吗?', '提示', {
          type: 'warning'
        })
          .then(() => {
            const loading = this.$loading({ lock: true });
            removeProduct(this.selection.map((d) => d.id))
              .then((msg) => {
                loading.close();
                this.$message.success(msg);
                this.reload();
              })
              .catch((e) => {
                loading.close();
                this.$message.error(e.message);
              });
          })
          .catch(() => {});
      },
      /* 更改状态 */
      editStatus(row) {
        const loading = this.$loading({ lock: true });
        updateProductStatus(row.id, row.status)
          .then((msg) => {
            loading.close();
            this.$message.success(msg);
            // this.reload();
          })
          .catch((e) => {
            loading.close();
            this.$message.error(e.message);
          });
      },
      /* 重置搜索 */
      reset() {
        this.where = {
          selectedCar: {
            brandId: null,
            seriesId: null,
            modelId: null
          }
        };
        // 更新 key 强制组件重新渲染
        this.componentKey = Date.now();
      },
      handleCarChange(carInfo) {
        this.where.selectedCar = carInfo;
      },
      showAllCityName(row) {
        this.showCityName = true;
        this.cityNames = row.cityName;
      }
    }
  };
</script>
<style scoped>
  .table-image {
    width: 100px;
    height: 80px;
    margin-right: 5px;
  }
  .table-text {
    /* 文本样式 */
    overflow: hidden;
  }
  .el-dialog__body {
    padding: 0;
  }
  /* 容器确保图片居中 */
  .image-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
  }
  /* 图片样式 */
  .sliding-image {
    max-width: 100%;
    height: 100%;
    display: block;
    margin: 0 auto;
  }
  ::v-deep .el-cascader__tags input::-webkit-input-placeholder {
    color: white;
    opacity: 0;
  }
</style>
