<template>
  <div class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <div class="filter-container">
      <el-input
        v-model="listQuery.search_name"
        type="text"
        placeholder="店铺名"
        class="filter-item"
        style="width:300px"
      />
      <el-select v-model="listQuery.type" class="filter-item">
        <el-option label="全部" value="" />
        <el-option label="工作室" value="1" />
        <el-option label="优享店" value="3" />
        <el-option label="体验店" value="2" />
      </el-select>
      <el-button
        type="primary"
        icon="el-icon-search"
        class="filter-item"
        @click="listQuery.page_index = 1;getStoreList();"
      >搜索</el-button>
      <el-button
        type="primary"
        icon="el-icon-edit"
        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="3" :disabled="storeForm.member.length > 1">优享店</el-radio>
            <el-radio :label="2">体验店</el-radio>
          </el-radio-group>
          <div>
            <i class="el-icon-info">工作室可以由销售经理和代理公司组成,体验店和优享店均为代理公司</i>
            <br>
            <i class="el-icon-info">工作室和优享店只能由1个人组成,体验店可以有2个人组成</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="size">
          <el-input
            v-model="storeForm.size"
            type="text"
            placeholder="门店面积大小"
          />
        </el-form-item>
        <el-form-item label="门店装修金额:" prop="decorate">
          <el-input
            v-model="storeForm.decorate"
            type="text"
            placeholder="门店装修金额"
          />
        </el-form-item>
        <el-form-item label="上传图片:">
          <el-upload
            action=""
            list-type="picture-card"
            :multiple="true"
            :http-request="httpRequestUpload"
            :file-list="storeImgList"
            :on-preview="handleStorePreview"
            :on-remove="handleStoreDelete"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </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.type === 3) && storeForm.member.length > 0) || (+storeForm.type === 2 && storeForm.member.length >= 2)"
            @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>
    <el-dialog :visible.sync="visible.add_img">
      <img width="100%" :src="visible.add_img_url" alt="">
    </el-dialog>
  </div>
</template>

<script>
// api
import {
  getStoreList,
  addStore,
  deleteStore,
  editStore,
  uploadstore
} from '@/api/shop/index'
// 获取数据
import {
  filterSet
} from '@/filters/systemSet'
// 省市区json
import provinces from '@/assets/json/area'
// import { regionData } from 'element-china-area-data'
import { eachReplaceKey } from '@/utils/city'
import compress from '@/utils/compress'
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,
        search_name: '',
        type: ''
      },
      visible: {
        store: false,
        type: 'add',
        add_img: false,
        add_img_url: ''
      },
      provinces: provinces,
      storeForm: {
        name: '',
        contents: '',
        type: 1,
        address: '',
        area: '',
        member: [],
        stationMobile: '',
        size: '',
        decorate: ''
      },
      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' }
        ],
        size: [
          { required: true, message: '请填写门店大小', trigger: 'blur' }
        ],
        member: [
          { required: true, validator: member, trigger: 'change' }
        ],
        decorate: [
          { required: true, message: '请填写门店装修金额', trigger: 'blur' }
        ]
      },
      setting: [],
      loadingFull: false,
      storeImgList: []
    }
  },
  created() {
    this.getStoreList()
    this.provinces = eachReplaceKey(provinces)
  },
  methods: {
    handleStorePreview(file) {
      this.visible.add_img = true
      this.visible.add_img_url = file.url
    },
    handleStoreDelete(file) {
      this.storeImgList = this.storeImgList.filter(a => a.uid !== file.uid)
      console.log(this.storeImgList)
    },
    async httpRequestUpload({ file }) {
      const formdata = new FormData()
      formdata.append('file', await compress(file))
      uploadstore(formdata).then(res => {
        if (res.code === 200) {
          this.storeImgList.push({
            name: file.name,
            uid: file.uid,
            url: res.data
          })
        }
      })
    },
    // 获取销售升级
    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.memberMobile = ''
      this.storeForm = {
        name: '',
        contents: '',
        type: 1,
        address: '',
        area: '',
        member: [],
        stationMobile: '',
        size: '',
        decorate: ''
      }
      this.storeImgList = []
    },
    // 添加成员
    setAddMember() {
      if (!this.memberMobile) {
        this.$message.warning('请输入店铺成员手机号!!')
        return false
      }
      if (+this.storeForm.type === 1 || +this.storeForm.type === 3) {
        if (this.storeForm.member.length > 1) {
          this.$message.warning('工作室和优享店成员有且仅有1个')
          return false
        }
      } else {
        if (this.storeForm.member.length > 2) {
          this.$message.warning('体验店成员最多为2个')
          return false
        }
      }
      if (this.storeForm.member.some(a => a === this.memberMobile)) {
        this.$message.warning('手机号已存在')
        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, size, decorate } = this.storeForm
          const img = []
          this.storeImgList.forEach(i => {
            img.push(i.url)
          })
          if (this.visible.type === 'add') {
            this.addStore({
              name,
              contents,
              address,
              type,
              province: area[0],
              city: area[1],
              area: area[2],
              member,
              stationMobile,
              size,
              img,
              decorate
            })
          } else {
            this.editStore({
              id: this.storeId,
              name,
              contents,
              address,
              type,
              province: area[0],
              city: area[1],
              area: area[2],
              member,
              stationMobile,
              size,
              img,
              decorate
            })
          }
        } 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) {
        console.log(e)
        this.$message.error('请求失败')
      }
    },
    // 删除店铺
    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) {
        console.log(e)
        this.$message.error('请求失败')
      }
    },
    // 修改门店
    handleEditStore(row) {
      const { id, name, contents, type, province, city, area, address, agent, manager, size, img } = 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 && manager.mobile || ''
      this.storeForm.size = size || ''
      this.storeImgList = []
      const imgs = img ? JSON.parse(img) : []
      imgs.forEach((item, i) => {
        this.storeImgList.push({
          name: '',
          uid: i,
          url: item
        })
      })
      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) {
        console.log(e)
        this.$message.error('请求失败')
      }
    }
  }
}
</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>
