<template>
  <div style="padding: 20px;">
    <!-- 搜索 -->
    <div style="padding: 0 0 10px;">
      <el-button type="primary" size="mini" @click="handleAddRelationshipLevel">新增平台关系等级</el-button>
      <el-button type="primary" size="mini" plain @click="handleSearch">查询</el-button>
      <el-button type="info" size="mini" plain @click="handleClear">重置</el-button>
    </div>
    <!-- 表格 -->
    <div>
      <el-table
        ref="multipleTable" :data="tableData" border
        :header-cell-style="{ background: '#EEF3FF', color: '#333333' }" tooltip-effect="dark" style="width: 100%"
      >
        <el-table-column align="center" prop="levelName" label="等级名称" />
        <el-table-column align="center" prop="levelNum" label="等级编号" />
        <el-table-column align="center" label="等级图标" prop="levelLogo">
          <template slot-scope="{ row }">
            <el-image
              v-if="row.levelLogo" :src="row.levelLogo" style="width:40px;height:40px;" fit="cover"
              :preview-src-list="[ row.levelLogo ]"
            />
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="levelReason" label="关系等级说明" />
        <el-table-column align="center" width="120" label="是否开启自购分佣" prop="ifSelf">
          <template slot-scope="{ row }">
            <el-tag v-if="row.ifSelf === 1" type="success" effect="plain">是</el-tag>
            <el-tag v-else-if="row.ifSelf === 0" type="info" effect="plain">否</el-tag>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="120" label="是否勾选累计分销金额" prop="ifMoney">
          <template slot-scope="{ row }">
            <el-tag v-if="row.ifMoney === 1" type="success" effect="plain">是</el-tag>
            <el-tag v-else-if="row.ifMoney === 0" type="info" effect="plain">否</el-tag>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="120" label="是否购买指定商品" prop="ifProduct">
          <template slot-scope="{ row }">
            <el-tag v-if="row.ifProduct === 1" type="success" effect="plain">是</el-tag>
            <el-tag v-else-if="row.ifProduct === 0" type="info" effect="plain">否</el-tag>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="120" label="是否勾选客户" prop="ifCustomer">
          <template slot-scope="{ row }">
            <el-tag v-if="row.ifCustomer === 1" type="success" effect="plain">是</el-tag>
            <el-tag v-else-if="row.ifCustomer === 0" type="info" effect="plain">否</el-tag>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="conditionMoney" label="累计分销金额" />
        <el-table-column align="center" prop="conditionInvitation" label="邀请下级满人数" />
        <el-table-column align="center" prop="conditionProduct" label="指定商品" />
        <el-table-column align="center" prop="conditionCustomer" label="客户满人数" />
        <el-table-column align="center" prop="shopId" label="商家ID" />
        <el-table-column align="center" prop="adminId" label="平台ID" />
        <el-table-column align="center" prop="proportion" label="分佣金额" />
        <el-table-column align="center" prop="directProportion" label="直接分佣比例" />
        <el-table-column align="center" prop="indirectProportion" label="间接分佣比例" />
        <el-table-column align="center" prop="directNum" label="直接分佣金额" />
        <el-table-column align="center" prop="indirectNum" label="间接分佣金额" />
        <el-table-column align="center" prop="manageArea" label="区域ID" />
        <el-table-column align="center" label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <div>
              <el-button type="text" @click="handleEditRelationshipLevel(scope.row)">编辑</el-button>
              <!-- <el-button type="text" @click="handleDeleteRelationshipLevel(scope.row)">删除</el-button> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination
          :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="10"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增或编辑表单 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '新增会员等级' : '修改会员等级'" :visible.sync="dialogFormVisible" width="800px" center
      :close-on-click-modal="false"
    >
      <div>
        <el-form ref="dataForm" :model="formData" label-width="140px" :rules="rules">
          <el-form-item label="等级名称" prop="levelName">
            <el-input v-model="formData.levelName" maxlength="20" placeholder="请输入等级名称" />
          </el-form-item>
          <el-form-item label="等级编号" prop="levelNum">
            <el-input v-model="formData.levelNum" type="number" placeholder="请输入等级编号" />
          </el-form-item>
          <el-form-item label="等级图标" prop="levelLogo">
            <el-upload class="avatar-uploader" :action="action" :show-file-list="false" :on-success="handleIconSuccess">
              <img v-if="formData.levelLogo" :src="formData.levelLogo" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
            <p style="line-height: 0px;color: #999999;">建议尺寸：100*100像素，jpg、png图片类型</p>
          </el-form-item>
          <el-form-item label="关系等级说明" prop="levelReason">
            <el-input v-model="formData.levelReason" maxlength="200" type="textarea" placeholder="请输入关系等级说明" />
          </el-form-item>
          <!-- <el-form-item label="是否开启自购分佣" prop="ifSelf">
            <el-radio-group v-model="formData.ifSelf">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
            </el-radio-group>
            </el-form-item>
            <el-form-item label="是否勾选累计消费金额" prop="ifMoney">
            <el-radio-group v-model="formData.ifMoney">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
            </el-radio-group>
            </el-form-item> -->
          <el-form-item label="是否购买指定商品" prop="ifProduct">
            <el-radio-group v-model="formData.ifProduct">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
            <el-button v-if="formData.ifProduct == 1" size="small" style="margin-left: 20px;" type="primary" @click="showAddShoping = true">选择分销商品</el-button>
            <!-- <el-input size="small" style="width: 260px;margin-left: 20px;"  v-if="formData.ifProduct == 1" v-model="formData.conditionProduct" placeholder="请选择指定商品" /> -->
          </el-form-item>
          <el-form-item label="是否开启邀请人数" prop="ifMoney">
            <el-radio-group v-model="formData.ifMoney">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
            <el-input v-if="formData.ifMoney == 1" v-model="formData.conditionInvitation" size="small" style="width: 260px;margin-left: 20px;" type="number" placeholder="请输入满足升级条件所需要的总人数" />
          </el-form-item>
          <el-form-item label="是否勾选团长客户" prop="ifCustomer">
            <el-radio-group v-model="formData.ifCustomer">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
            <el-input v-if="formData.ifCustomer == 1" v-model="formData.conditionCustomer" size="small" style="width: 260px;margin-left: 20px;" type="number" placeholder="满足升级条件的团长数" />
          </el-form-item>
          <el-form-item label="累计分销金额" prop="conditionMoney">
            <el-input v-model="formData.conditionMoney" style="width: 300px" type="number" placeholder="请输入累计分销金额" />
          </el-form-item>
          <!-- <el-form-item label="邀请下级满人数" prop="conditionInvitation">
            <el-input v-model="formData.conditionInvitation" type="number" placeholder="请输入邀请下级满人数" />
            </el-form-item> -->
          <!-- <el-form-item label="指定商品" prop="conditionProduct">
            <el-input v-model="formData.conditionProduct" placeholder="请输入指定商品（逗号隔开）" />
            </el-form-item> -->
          <!-- <el-form-item label="商家ID" prop="shopId">
            <el-input v-model="formData.shopId" type="number" placeholder="请输入商家ID" />
            </el-form-item>
            <el-form-item label="平台ID" prop="adminId">
            <el-input v-model="formData.adminId" type="number" placeholder="请输入平台ID" />
            </el-form-item> -->
          <el-form-item label="分佣形式配置" prop="proportion">
            <el-radio-group v-model="formData.proportion">
              <el-radio :label="1">比例</el-radio>
              <el-radio :label="2">金额</el-radio>
            </el-radio-group>
            <!-- <el-input v-model="formData.proportion" type="number" placeholder="请输入分佣金额" /> -->
          </el-form-item>
          <template v-if="formData.proportion == 1">
            <el-form-item label="直接分佣比例 (%)" prop="directProportion">
              <el-input-number v-model.number="formData.directProportion" :min="0" :max="99"></el-input-number>
            </el-form-item>
            <el-form-item label="间接分佣比例 (%)" prop="indirectProportion">
              <el-input-number v-model.number="formData.indirectProportion" :min="0" :max="99"></el-input-number>
              <!-- <el-input v-model="formData.indirectProportion" type="number" placeholder="请输入间接分佣金额（整数，最大99）" /> -->
            </el-form-item>
          </template>
          <template v-if="formData.proportion == 2">
            <!-- <div style="display: flex;"> -->
            <el-form-item label="直接分佣金额" prop="directNum">
              <el-input v-model.number="formData.directNum" style="width: 300px" type="number" placeholder="请输入直接分佣金额" />
            </el-form-item>
            <el-form-item label="间接分佣金额" prop="indirectNum">
              <el-input v-model.number="formData.indirectNum" style="width: 300px" type="number" placeholder="请输入间接分佣金额" />
            </el-form-item>
            <!-- </div> -->
          </template>
          <el-form-item label="区域ID" prop="manageArea">
            <el-cascader
              ref="cascaderRef" :props="areaData"
              @change="handleCascaderChange"
            ></el-cascader>
            <!-- <el-input v-model="formData.manageArea" type="number" placeholder="请选择区域ID" /> -->
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
          <el-button v-if="dialogStatus == 'update'" type="primary" @click="updateData">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-drawer
      title="已选商品"
      :visible.sync="showAddShoping"
      :append-to-body="true"
      size="50%"
      :before-close="() => showAddShoping = false"
    >
      <!-- <el-button style="margin-left: 20px" size="small" type="primary" @click="innerDrawer = true">添加商品</el-button> -->
      <div class="shopContainer">
        <el-table
          ref="multipleTable" :data="shopList" border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }" tooltip-effect="dark" style="width: 100%"
          max-height="620" @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40px" />
          <el-table-column label="产品主图" width="100" align="center">
            <template slot-scope="scope">
              <img height="80" width="80" :src="scope.row.image" alt srcset>
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="产品名称" width="160" align="center" />
          <el-table-column prop="originalPrice" label="价格（元）" align="center" show-overflow-tooltip />
          <el-table-column prop="stockNumber" label="库存（件）" align="center" show-overflow-tooltip />
        </el-table>
        <div style="display: flex;justify-content: center;align-items: center;box-sizing: border-box;padding: 10px;">
          <el-button type="primary" @click="showAddShoping = false">确定</el-button>
        </div>
      </div>
      <!-- <el-drawer
        title="选择商品"
        :append-to-body="true"
        size="40%"
        :before-close="() => innerDrawer = false"
        :visible.sync="innerDrawer">
        <el-table
        ref="multipleTable" :data="shopList" border
        :header-cell-style="{ background: '#EEF3FF', color: '#333333' }" tooltip-effect="dark" style="width: 100%"
        max-height="620" @selection-change="handleSelectionChange"
        >
        <el-table-column type="selection" width="40px" />
        <el-table-column label="产品主图" width="100" align="center">
        <template slot-scope="scope">
        <img height="80" width="80" :src="scope.row.image" alt srcset>
        </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称" width="160" align="center" />
        <el-table-column prop="originalPrice" label="价格（元）" align="center" show-overflow-tooltip />
        <el-table-column prop="stockNumber" label="库存（件）" align="center" show-overflow-tooltip />
        </el-table>
        <div style="display: flex;justify-content: center;align-items: center;box-sizing: border-box;padding: 10px;">
        <el-button type="primary">确定</el-button>
        </div>
        </el-drawer> -->
    </el-drawer>
  </div>
</template>

<script>
import {
  getByIdPlatformRelationshipLevel,
  getAllPlatformRelationshipLevel,
  savePlatformRelationshipLevel,
  updatePlatformRelationshipLevel
} from '@/api/relationshipChainManagement/relationshipLevel'
import { getClassifyGetAll } from '@/api/commodity'
import { uploadUrl } from '@/utils/request'
import { getProvinceList, getChildAreaList } from '@/api/address'
import { get } from 'js-cookie'
export default {
  name: 'RelationshipLevel',
  data() {
    return {
      showAddShoping: false, // 控制商品添加的展示
      innerDrawer: false, // 子级抽屉的开关
      areaData: {
        lazy: true,
        label: 'name',
        value: 'id',
        checkStrictly: true,
        lazyLoad(node, resolve) {
          const { level, value } = node
          if (level === 0) {
            getProvinceList().then((res) => {
              resolve(res.data)
            })
          } else if (level != 0) {
            getChildAreaList(value).then((res) => {
              resolve(res.data.map((item) => {
                item.leaf = level === 3
                return item
              }))
            })
          }
        }
      },
      listQuery: {
        relationshipLevelId: '',
        page: 1,
        pageSize: 10
      },
      shopListQuery: {
        page: 1,
        pageSize: 100,
        productId: '',
        productName: '',
        shelveState: '',
        shopName: '',
        classifyId: 1439
      },
      shopList: [],
      shopTotal: 0,
      total: 1,
      tableData: [],
      currentPage: 1,
      dialogStatus: '',
      action: uploadUrl,
      formData: {
        relationshipLevelId: '',
        levelName: '',
        levelNum: '',
        levelLogo: '',
        levelReason: '',
        ifSelf: 0,
        ifMoney: 0,
        ifProduct: 0,
        // ifInvitation: 0,
        ifCustomer: 0,
        conditionMoney: '',
        conditionInvitation: '',
        conditionProduct: '',
        conditionCustomer: '',
        shopId: '',
        adminId: '',
        proportion: 1,
        directProportion: '0',
        indirectProportion: '0',
        directNum: 0,
        indirectNum: 0,
        manageArea: ''
      },
      dialogFormVisible: false,
      rules: {
        levelName: [ { required: true, message: '请输入等级名称', trigger: 'blur' } ],
        levelNum: [ { required: true, message: '请输等级编号', trigger: 'blur' } ],
        levelLogo: [ { required: true, message: '请输入会员成长值', trigger: 'blur' } ],
        directProportion: [ { required: true, message: '直接分佣比例不能为空或小于零', trigger: 'blur' } ],
        indirectProportion: [ { required: true, message: '间接分佣比例不能为空或小于零', trigger: 'blur' } ],
        directNum: [{ required: true, message: '直接分佣金额不能为空或小于零', trigger: 'blur' }, { type: 'number', message: '金额必须为数字值' }],
        indirectNum: [{ required: true, message: '间接分佣金额不能为空或小于零', trigger: 'blur' }, { type: 'number', message: '金额必须为数字值' }]
      }
    }
  },
  computed: {

  },
  mounted() {
    this.getList()
    this.getShopList()
  },
  methods: {
    async getShopList() { // 查询可供选择的分销商品数据
      const res = await getClassifyGetAll(this.shopListQuery)
      this.shopList = res.data.list
      this.shopTotal = res.data.total
      // console.log(res);
    },
    handleSelectionChange(val) {
      console.log(val)
      const arr = []
      val.forEach((item, index) => {
        arr.push(item.productId)
      })
      this.formData.conditionProduct = arr.join()
      // console.log(this.formData.conditionProduct);
      // this.multipleSelection = val
      // this.groupData.ids = []
    },
    // 初始化查询所有数据
    async getList() {
      const res = await getAllPlatformRelationshipLevel(this.listQuery)
      this.tableData = res.data.records
      this.total = res.data.total
    },
    handleIconSuccess(response) {
      this.formData.levelLogo = response.data.url
      this.$forceUpdate()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    // 查询
    handleSearch() {
      this.total = 1
      this.listQuery.page = 1
      this.getList()
    },
    // 清除
    handleClear() {
      this.listQuery = {
        relationshipLevelId: '',
        page: 1,
        pageSize: 10
      }
      this.getList()
    },
    // 新增平台关系等级
    handleAddRelationshipLevel() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.resetForm()
    },
    resetForm() {
      this.formData = {
        relationshipLevelId: '',
        levelName: '',
        levelNum: '',
        levelLogo: '',
        levelReason: '',
        ifSelf: 0,
        ifMoney: 0,
        ifProduct: 0,
        ifCustomer: 0,
        conditionMoney: '',
        conditionInvitation: '',
        conditionProduct: '',
        conditionCustomer: '',
        shopId: '',
        adminId: '',
        proportion: 1,
        directProportion: '0',
        indirectProportion: '0',
        directNum: 0,
        indirectNum: 0,
        manageArea: ''
      }
    },
    // 编辑平台关系等级
    handleEditRelationshipLevel(row) {
      this.resetForm()
      // getByIdPlatformRelationshipLevel({ relationshipLevelId: row.relationshipLevelId })
      //   .then((res) => {
      //     this.formData = res.data
      //   })
      for (const key in this.formData) {
        this.formData[key] = row[key]
      }
      // this.formData.relationshipLevelId = row.relationshipLevelId
      console.log(this.formData)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    // 删除平台关系等级
    handleDeleteRelationshipLevel(row) {
      this.$confirm('是否继续删除此平台关系等级?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deletePlatformRelationshipLevel({ relationshipLevelId: row.relationshipLevelId })
            .then((res) => {
              if (res.code === '') {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              }
              this.getList()
            })
        })
    },
    // 提交平台关系等级
    createData() {
      this.$refs.dataForm.validate((valid) => {
        // console.log(valid);
        // console.log(this.formData);
        if (valid) {
          savePlatformRelationshipLevel(this.formData)
            .then((response) => {
              this.dialogFormVisible = false
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.getList()
            })
            .catch((response) => {
              this.$message({
                message: '新增失败',
                type: 'error'
              })
            })
        }
      })
    },
    updateData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          updatePlatformRelationshipLevel(this.formData)
            .then(() => {
              this.getList()
              this.dialogFormVisible = false
              this.$message({
                message: '修改成功',
                type: 'success'
              })
            })
            .catch((response) => {
              this.$message({
                message: '修改失败',
                type: 'error'
              })
            })
        }
      })
    },
    // 获取省数据
    handleCascaderChange() {
      const checkedNode = this.$refs.cascaderRef.getCheckedNodes()
      // console.log(checkedNode);
      const nodeData = checkedNode[0].data
      this.formData.manageArea = nodeData.id
    }
  }
}
</script>

<style lang='less' scoped>
.shopContainer {
  position: relative;
  box-sizing: border-box;
  padding: 20px;
}
@import url("../../../styles/elDialog.scss");
.avatar-uploader {
	/deep/ .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
}

.avatar-uploader {
	/deep/ .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>
