<template>
  <div class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <div class="filter-container">
      <el-button
        type="primary"
        icon="el-icon-edit"
        size="mini"
        class="filter-item"
        @click="() => { visible.store = true; visible.type = 'add' }"
      >
        添加店铺
      </el-button>
    </div>

    <el-table
      :data="table"
      :header-cell-style="{ background: '#f8fbfc' }"
      class="tableBorder"
      border
      stripe
    >
      <el-table-column
        prop="name"
        align="center"
        label="店铺名"
      />
      <el-table-column
        prop="type"
        align="center"
        label="店铺类型"
      >
        <template
          slot-scope="{ row }"
        >
          {{ row.type === 1 ? '工作室' : (row.type === 2 ? '体验店' : '优享店') }}
        </template>
      </el-table-column>
      <el-table-column
        prop="contents"
        align="center"
        label="店铺描述"
      >
        <template
          slot-scope="{ row }"
        >
          {{ row.contents ? row.contents : '暂无描述' }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="详细地址"
      >
        <template
          slot-scope="{ row }"
        >
          {{ `${row.province}${row.city}${row.area}${row.address}` }}
        </template>
      </el-table-column>
      <el-table-column
        prop="agent"
        align="center"
        label="组成销售"
      >
        <template
          slot-scope="{ row }"
        >
          <div
            v-for="item in row.agent"
            :key="item.id"
            class="users-item"
          >
            <el-tag
              v-if="item.id === row.manager.id"
              size="mini"
            >
              负责人
            </el-tag>
            <p class="user-name">{{ item.nickname }}({{ item.level === 3 ? '代理公司' : '销售经理' }})</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="150"
        align="center"
      >
        <template
          slot-scope="{ row }"
        >
          <el-button
            type="primary"
            size="mini"
            @click="handleEditStore(row)"
          >
            修改
          </el-button>
          <el-button
            size="mini"
            @click="handleDeleteStore(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      :total="tableTotal"
      :limit="listQuery.page_size"
      :page="listQuery.page_index"
      @pagination="changePagination"
      @update:limit="changePagination"
    />
    <!-- 添加店铺 -->
    <el-dialog
      :title="visible.type === 'add' ? '添加店铺' : '修改店铺'"
      :visible.sync="visible.store"
      :close-on-click-modal="false"
      :before-close="setResetStoreForm"
    >
      <el-form
        ref="storeForm"
        :model="storeForm"
        :rules="storeRules"
        label-width="120px"
      >
        <el-form-item label="门店名:" prop="name">
          <el-input
            v-model="storeForm.name"
            placeholder="门店名"
          />
        </el-form-item>
        <el-form-item label="门店描述:" prop="contents">
          <el-input
            v-model="storeForm.contents"
            type="textarea"
            placeholder="门店描述"
          />
        </el-form-item>
        <el-form-item label="门店类型:" prop="type">
          <el-radio-group
            v-model="storeForm.type"
          >
            <el-radio :label="1" :disabled="storeForm.member.length > 1">工作室</el-radio>
            <el-radio :label="2">体验店</el-radio>
            <el-radio :label="3">优享店</el-radio>
          </el-radio-group>
          <div>
            <i class="el-icon-info">工作室可以由特级组成,体验店和优享店均为皇冠组成</i>
            <br>
            <i class="el-icon-info">工作室只能由1个人组成,体验店和优享店可以为多个人组成</i>
          </div>
        </el-form-item>
        <el-form-item label="所在地区:" prop="area">
          <el-cascader
            v-model="storeForm.area"
            :options="provinces"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="storeForm.address"
            type="textarea"
            placeholder="详细地址,例如:xx街道xx号"
          />
        </el-form-item>
        <el-form-item label="店铺成员:" prop="member">
          <el-input
            v-model="memberMobile"
            placeholder="成员手机号"
            style="width: 200px"
            minlength="11"
            maxlength="11"
            show-word-limit
          />
          <el-button
            type="primary"
            :disabled="storeForm.type === 1 && storeForm.member.length > 0"
            @click="setAddMember"
          >
            添加
          </el-button>
        </el-form-item>
        <el-form-item>
          <div
            v-for="(item, i) in storeForm.member"
            :key="i"
          >
            <el-radio
              v-model="storeForm.stationMobile"
              :label="item"
            >
              {{ item }}
            </el-radio>
            <i
              class="el-icon-delete"
              style="cursor:pointer;"
              @click="setDeleteMember(i)"
            />
          </div>
          <div>
            <i class="el-icon-warning">以选中的成员所在战区为店铺所在战区</i>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            @click="setResetStoreForm"
          >
            取消
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleSubmitStore"
          >
            提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// api
import {
  getStoreList,
  addStore,
  deleteStore,
  editStore
} from '@/api/system/next'
// 获取数据
import {
  filterSet
} from '@/filters/systemSet'
// 省市区json
import provinces from '@/assets/json/provinces'
export default {
  name: 'NextSet',
  data() {
    const member = (rule, value, callback) => {
      if (this.storeForm.member.length < 1) {
        callback(new Error('请添加店铺成员'))
      } else {
        callback()
      }
    }

    return {
      tabPaneType: '0',
      table: [],
      tableTotal: 0,
      listQuery: {
        page_size: 20,
        page_index: 1
      },
      visible: {
        store: false,
        type: 'add'
      },
      provinces: provinces,
      storeForm: {
        name: '',
        contents: '',
        type: 1,
        address: '',
        area: '',
        member: [],
        stationMobile: ''
      },
      memberMobile: '',
      storeId: '',
      storeRules: {
        name: [
          { required: true, message: '请填写门店名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择门店类型', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请填写门店详细地址', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请选择门店所在地区', trigger: 'change' }
        ],
        member: [
          { required: true, validator: member, trigger: 'change' }
        ]
      },
      setting: [],
      loadingFull: false
    }
  },
  methods: {
    // 获取销售升级
    getLevel() {
      const data = this.setting
      // 时间
      const time = filterSet(data, 'activity_time').values.split('/')
      this.level.time = time
      // 销售经理/销售主管门槛
      const price = filterSet(data, 'upgrade_standard').values.split('/')
      this.level.tjMoney = price[0] ? price[0] : ''
      this.level.djMoney = price[1] ? price[1] : ''
      // 活动状态
      let status = filterSet(data, 'activity_start').values
      status = status === '1'
      this.level.status = status
    },
    // 获取门店
    async getStoreList() {
      this.loadingFull = true
      try {
        const res = await getStoreList(this.listQuery)
        const { message, code } = res
        if (code === 200) {
          const { data } = res
          const { list, total } = data
          this.table = list
          this.tableTotal = total
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`门店设置失败: ${e}`)
      }
      this.loadingFull = false
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.listQuery.page_size = limit
      this.listQuery.page_index = page
      this.getStoreList()
    },
    // 关闭重置
    setResetStoreForm() {
      this.visible.store = false
      this.$refs.storeForm.resetFields()
      this.storeForm.member = []
      this.storeForm.stationMobile = ''
      this.memberMobile = ''
    },
    // 添加成员
    setAddMember() {
      if (!this.memberMobile) {
        this.$message.warning('请输入店铺成员手机号!!')
        return false
      }
      if (this.storeForm.type === '1' || this.storeForm.type === 1) {
        if (this.storeForm.member.length > 0) {
          this.$message.warning('工作室成员有且仅有1个')
          return false
        }
      }
      this.storeForm.member.push(this.memberMobile)
      if (this.storeForm.member.length === 1) {
        this.storeForm.stationMobile = this.storeForm.member[0]
      }
      this.memberMobile = ''
    },
    // 删除成员
    setDeleteMember(i) {
      this.storeForm.member.splice(i, 1)
      if (this.storeForm.member.length === 1) {
        this.storeForm.stationMobile = this.storeForm.member[0]
      }
    },
    // 添加店铺
    handleSubmitStore() {
      this.$refs.storeForm.validate((valid) => {
        if (valid) {
          if (this.storeForm.member.length < 0) {
            this.$message.warning('请添加店铺成员')
            return false
          }
          if (this.storeForm.stationMobile === '') {
            this.$message.warning('请确定店铺战区')
            return false
          }
          const { name, contents, address, area, type, member, stationMobile } = this.storeForm

          if (this.visible.type === 'add') {
            this.addStore({
              name,
              contents,
              address,
              type,
              province: area[0],
              city: area[1],
              area: area[2],
              member,
              stationMobile
            })
          } else {
            this.editStore({
              id: this.storeId,
              name,
              contents,
              address,
              type,
              province: area[0],
              city: area[1],
              area: area[2],
              member,
              stationMobile
            })
          }
        } else {
          return false
        }
      })
    },
    // 提交添加
    async addStore(data) {
      const res = await addStore(data)
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success(message)
          this.setResetStoreForm()
          this.getStoreList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        let message = res.message ? res.message : e.message
        message = e.message ? e.message : '请求失败'
        this.$message.error(message)
      }
    },
    // 删除店铺
    handleDeleteStore(row) {
      const { id, name } = row
      this.$confirm(`确认删除${name}?`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteStore(id)
      })
    },
    // 删除店铺
    async deleteStore(id) {
      const res = await deleteStore({ id })
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success(message)
          this.getStoreList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        let message = res.message ? res.message : e.message
        message = e.message ? e.message : '请求失败'
        this.$message.error(message)
      }
    },
    // 修改门店
    handleEditStore(row) {
      const { id, name, contents, type, province, city, area, address, agent, manager } = row
      // 赋值
      this.storeForm.name = name
      this.storeForm.contents = contents
      this.storeForm.type = type
      this.storeForm.area = [province, city, area]
      this.storeForm.address = address
      this.storeForm.member = agent.map(item => {
        return item.mobile
      })
      this.storeForm.stationMobile = manager.mobile
      this.storeId = id
      this.visible.type = 'edit'
      this.visible.store = true
    },
    // 修改
    async editStore(data) {
      const res = await editStore(data)
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success(message)
          this.setResetStoreForm()
          this.storeId = ''
          this.getStoreList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        let message = res.message ? res.message : e.message
        message = e.message ? e.message : '请求失败'
        this.$message.error(message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .users-item{
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;

    &:nth-last-of-type(1){
      margin-bottom: 0;
    }

    .user-name,.user-level,.icon{
      margin: 0 5px;
    }

    .icon{
      transform: scale(1.2);
      cursor: pointer;
    }
  }
</style>
