<template>
  <div class="app-container">
    <el-input
      v-model="searchParams.search_user"
      type="text"
      placeholder="代理姓名 / 手机号"
      style="width: 300px"
      @keyup.enter.native="
        searchParams.page_index = 1;
        getStudioList();
      "
    />
    <el-input
      v-model="searchParams.search_content"
      type="text"
      placeholder="店铺名称"
      style="width: 300px"
      @keyup.enter.native="
        searchParams.page_index = 1;
        getStudioList();
      "
    />
    <el-select v-model="searchParams.activity_id" style="width: 300px">
      <el-option label="全部" value="" />
      <el-option
        v-for="item in activitys"
        :key="item.id"
        :label="item.title"
        :value="item.id"
      />
    </el-select>
    <el-select v-model="searchParams.status" style="width: 200px">
      <el-option :value="0" label="正常" />
      <el-option :value="1" label="禁用" />
    </el-select>
    <el-button
      type="primary"
      @click="
        searchParams.page_index = 1;
        getStudioList();
      "
    >
      搜索
    </el-button>
    <el-button v-read-excel="importStock" type="primary" size="small">
      导入工作室
    </el-button>
    <el-button type="primary" @click="downloadTemplate"> 下载模板 </el-button>
    <el-button type="primary" @click="exportStock"> 导出 </el-button>
    <el-button type="primary" @click="dialogFormVisible = true">
      新增
    </el-button>
    <!-- 新增弹框 -->
    <el-dialog title="新增工作室" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="工作室名称:"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-col :span="10">
            <el-input v-model="form.name" autocomplete="off" />
          </el-col>
        </el-form-item>
        <el-form-item
          label="代理手机号:"
          :label-width="formLabelWidth"
          prop="mobile"
        >
          <el-col :span="10">
            <el-input v-model="form.mobile" autocomplete="off" width="300px" />
          </el-col>
        </el-form-item>
        <el-form-item
          label="工作室地址:"
          :label-width="formLabelWidth"
          prop="address"
        >
          <el-col :span="16">
            <el-cascader
              v-model="form.address"
              :options="provinces"
              :placeholder="'请选择省/市/区县'"
            />
            <!-- <el-cascader
              :options="regionData"
              @change="handleChange"
              :clearable="true"
              :placeholder="'请选择省/市/区县'"
            >
            </el-cascader> -->
          </el-col>
        </el-form-item>
        <el-form-item
          label="详细地址:"
          :label-width="formLabelWidth"
          prop="detailAddress"
        >
          <el-col :span="10">
            <el-input
              v-model="form.detailAddress"
              autocomplete="off"
              width="300px"
            />
          </el-col>
        </el-form-item>
        <el-form-item
          label="工作室状态:"
          :label-width="formLabelWidth"
          prop="radio"
        >
          <el-col :span="10">
            <el-radio v-model="form.radio" label="0">正常</el-radio>
            <el-radio v-model="form.radio" label="1">禁用</el-radio>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addStock('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-table
      border
      stripe
      :header-cell-style="{ background: '#f8fbfc' }"
      class="tableBorder"
      :data="list"
      style="margin-top: 20px"
      @sort-change="toSort"
    >
      <el-table-column type="index" label="序号" align="center" />
      <el-table-column prop="studio_name" label="工作室名称" align="center" />
      <el-table-column label="工作室地址" align="center">
        <template slot-scope="{ row }">
          {{
            `${row.province || ""}${row.city || ""}${row.area || ""}${
              row.address || ""
            }`
          }}
        </template>
      </el-table-column>
      <el-table-column label="负责人昵称" align="center">
        <template slot-scope="{ row }">
          {{ row.get_user && row.get_user.nickname }}
        </template>
      </el-table-column>
      <el-table-column label="负责人姓名" align="center">
        <template slot-scope="{ row }">
          {{ row.get_user && row.get_user.realname }}
        </template>
      </el-table-column>
      <el-table-column label="负责人手机号" align="center">
        <template slot-scope="{ row }">
          {{ row.get_user && row.get_user.mobile }}
        </template>
      </el-table-column>
      <el-table-column
        label="活动订单金额"
        align="center"
        prop="get_bonus.order_money"
        sortable="custom"
      >
        <template slot-scope="{ row }">
          {{
            row.get_bonus && row.get_bonus.order_money
              ? row.get_bonus && row.get_bonus.order_money
              : 0
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="产品补助金"
        align="center"
        prop="get_bonus.bonus"
        sortable="custom"
      >
        <template slot-scope="{ row }">
          {{
            row.get_bonus && row.get_bonus.bonus
              ? row.get_bonus && row.get_bonus.bonus
              : 0
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="已兑换"
        align="center"
        prop="get_bonus.exchange_bonus"
        sortable="custom"
      >
        <template slot-scope="{ row }">
          {{
            row.get_bonus && row.get_bonus.exchange_bonus
              ? row.get_bonus && row.get_bonus.exchange_bonus
              : 0
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button
            v-if="row.status === '0'"
            type="danger"
            plain
            @click="forBidden(row)"
          >禁用</el-button>
          <el-button
            v-else
            type="primary"
            plain
            @click="forBidden(row)"
          >启用</el-button>
          <el-button
            type="primary"
            @click="
              drawer = true;
              changeStudio(row);
            "
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="修改工作室" :visible.sync="drawer">
      <el-form :model="form">
        <el-form-item label="工作室名称:" :label-width="formLabelWidth">
          <el-col :span="10">
            <el-input v-model="form.name" autocomplete="off" />
          </el-col>
        </el-form-item>
        <el-form-item label="代理手机号:" :label-width="formLabelWidth">
          <el-col :span="10">
            <el-input v-model="form.mobile" autocomplete="off" width="300px" />
          </el-col>
        </el-form-item>
        <el-form-item label="工作室地址:" :label-width="formLabelWidth">
          <el-col :span="16">
            <el-cascader
              v-model="form.address"
              :options="provinces"
              :placeholder="'请选择省/市/区县'"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="详细地址:" :label-width="formLabelWidth">
          <el-col :span="10">
            <el-input
              v-model="form.detailAddress"
              autocomplete="off"
              width="300px"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="详细地址:" :label-width="formLabelWidth">
          <el-col :span="10">
            <el-radio v-model="form.radio" label="0">正常</el-radio>
            <el-radio v-model="form.radio" label="1">禁用</el-radio>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="drawer = false">取 消</el-button>
        <el-button type="primary" @click="sureStock">确 定</el-button>
      </div>
    </el-dialog>
    <pagination
      :total="total"
      :limit="searchParams.page_size"
      :page="searchParams.page_index"
      @pagination="changePagination"
      @update:limit="changePagination"
    />
  </div>
</template>
<script>
import { activityList } from '@/api/giftB'
import {
  studioList,
  importStudio,
  AddStudio,
  SetStatusStudio,
  UpdateStudio,
  exportstudio
} from '@/api/studio/index'
import provinces from '@/assets/json/area'
// import { regionData } from 'element-china-area-data'
import { eachReplaceKey } from '@/utils/city'
// import { param } from '@/utils'
export default {
  data() {
    return {
      drawer: false,
      dialogFormVisible: false,
      searchParams: {
        page_index: 1,
        page_size: 20,
        status: 0,
        search_user: '',
        search_content: '',
        activity_id: ''
      },
      activitys: [],
      list: [],
      total: 0,
      form: {
        id: '',
        name: '',
        mobile: '',
        address: '',
        detailAddress: '',
        radio: '0' // 0正常,1禁用
      },
      formLabelWidth: '120px',
      provinces: provinces,
      city: '河南省郑州市', // 省市县乡
      changeList: '',
      mobile: '', // 代理电话
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入', trigger: 'blur' }],
        address: [{ required: true, message: '请输入', trigger: 'blur' }],
        detailAddress: [{ required: true, message: '请输入', trigger: 'blur' }],
        radio: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  watch: {
    'searchParams.activity_id'() {
      this.searchParams.page_index = 1
      this.getStudioList()
    },
    'searchParams.status'() {
      this.searchParams.page_index = 1
      this.getStudioList()
    }
  },
  mounted() {
    this.provinces = eachReplaceKey(provinces)
    this.searchParams.sort = 1
    this.searchParams.sort_type = 0
    this.activityList(this.getStudioList)
  },
  methods: {
    async activityList(cb) {
      // 活动
      const loading = this.$loading()
      await activityList()
        .then((res) => {
          loading.close()
          if (res.code === 200) {
            this.activitys = res.data
            res.data.map((item) => {
              if (item.is_ing === 1) {
                this.searchParams.activity_id = item.id
              }
            })
          }
          cb && cb()
        })
        .catch((e) => {
          loading.close()
          cb && cb()
        })
    },
    getStudioList() {
      // 列表
      const loading = this.$loading()

      studioList(this.searchParams)
        .then((res) => {
          loading.close()
          if (res.code === 200) {
            this.list = res.data.list
            this.total = res.data.total
            console.log(res, 'ppp')
          } else {
            this.$message.error(res.message || '获取工作室列表失败')
          }
        })
        .catch(() => {
          loading.close()
          this.$message.error('获取工作室列表失败')
        })
    },
    changePagination(data) {
      // 分页
      const { page, limit } = data
      this.searchParams.page_size = limit
      this.searchParams.page_index = page
      this.getStudioList()
    },
    downloadTemplate() {
      // 下载模板
      const header = [
        '序号',
        '工作室名称',
        '代理公司手机号',
        '省份',
        '城市',
        '地区',
        '详细地址'
      ]
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: header,
          data: '',
          filename: '工作室信息',
          bookType: 'xlsx'
        })
      })
    },

    importStock(list) {
      this.loadingFull = true
      console.log(list, 'pppp')
      var names, result
      names = Object.create(null)
      list.forEach(function(o) {
        Object.keys(o).forEach(function(k) {
          names[k] = true
        })
      })
      result = Object.keys(names)
      console.log(result, '000000')
      const top = [
        '序号',
        '工作室名称',
        '代理公司手机号',
        '省份',
        '城市',
        '地区',
        '详细地址'
      ]
      // console.log(list1, 'list1')
      if (JSON.stringify(result) === JSON.stringify(top)) {
        console.log('xiangdeng')
        importStudio({
          data: list
        })
          .then((res) => {
            this.loadingFull = false
            if (res.code === 200) {
              this.$message.success(res.message || '成功')
              this.getGoodStock()
            } else {
              this.$message.error(res.message || '批量修改失败')
            }
          })
          .catch((e) => {
            this.loadingFull = false
          })
      } else {
        console.log('buxiangdeng ')
        this.$message.error('导入数据格式有误,请参照模板修改')
      }
    },
    forBidden(row) {
      // 禁用
      this.$confirm('此操作将禁用该工作室, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const params = {
            id: row.id
          }
          SetStatusStudio(params).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
              this.getStudioList()
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '操作取消'
          })
        })
    },
    exportStock() {
      // 导出
      this.loadingFull = true

      const params = {
        search_content: this.searchParams.search_content,
        status: this.searchParams.status,
        activity_id: this.searchParams.activity_id,
        search_user: this.searchParams.search_user
      }
      exportstudio(params).then((res) => {
        console.log(res, 'list')
        this.loadingFull = false
        // return;
        if (res.code === 200) {
          if (!res.data.list || res.data.list.length < 0) {
            this.$message.error('没有可导出数据')
          } else {
            const list = res.data.list
            import('@/vendor/Export2Excel').then((excel) => {
              excel.export_json_to_excel({
                header: Object.keys(list[0]),
                data: list.map((listItem) =>
                  Object.keys(list[0]).map((j) => listItem[j])
                ),
                filename: '工作室列表',
                bookType: 'xlsx'
              })
            })
            this.$message.success('导出成功')
          }
        } else {
          this.$message.error('导出失败')
        }
      })
    },
    addStock(formData) {
      // 新增
      this.dialogFormVisible = true
      const data = {
        studio_name: this.form.name,
        mobile: this.form.mobile,
        province: this.form.address[0],
        city: this.form.address[1],
        area: this.form.address[2],
        address: this.form.detailAddress,
        status: this.form.radio
      }
      this.$refs[formData].validate((valid) => {
        if (valid) {
          AddStudio(data)
            .then((res) => {
              if (res.code === 200) {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '新增工作室成功'
                })

                this.$refs[formData].resetFields() // 表单重置
                this.getStudioList()
              } else {
                this.$message({
                  type: 'info',
                  message: res.message
                })
              }
            })
            .catch((e) => {
              this.$message({
                type: 'error',
                message: '新增工作室失败'
              })
            })
          console.log(this.form.radio, 'addressS')
        }
      })
    },
    changeStudio(row) {
      // 修改工作室信息
      const city = [row.province, row.city, row.area]
      this.form = {
        id: row.id,
        name: row.studio_name,
        mobile: row.get_user.mobile,
        address: city,
        detailAddress: row.address,
        radio: row.status // 0正常,1禁用
      }
    },
    sureStock() {
      this.drawer = false
      const data = {
        id: this.form.id,
        studio_name: this.form.name,
        mobile: this.form.mobile,
        province: this.form.address[0],
        city: this.form.address[1],
        area: this.form.address[2],
        address: this.form.detailAddress,
        status: this.form.radio
      }
      UpdateStudio(data).then((res) => {
        if (res.code === 200) {
          this.dialogFormVisible = false
          this.$message({
            type: 'success',
            message: '工作室修改成功'
          })
          this.getStudioList()
        } else {
          this.dialogFormVisible = false
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    // 排序
    toSort({ column, prop, order }) {
      const sortMap = new Map([
        ['get_bonus.order_money', this.OrdeAmount],
        ['get_bonus.bonus', this.ProductGrants],
        ['get_bonus.exchange_bonus', this.exChange]
      ])
      console.log(sortMap, 'sortMap11')
      if (sortMap.get(prop)) {
        sortMap.get(prop)(order)
      }
    },
    exChange(sort) {
      // 已兑换
      this.searchParams.sort = sort && sort === 'ascending' ? 0 : 1
      this.searchParams.sort_type = 2
      this.getStudioList()
    },
    ProductGrants(sort) {
      // 产品补助金
      this.searchParams.sort = sort && sort === 'ascending' ? 0 : 1
      this.searchParams.sort_type = 1
      console.log(this.searchParams)
      this.getStudioList()
    },
    OrdeAmount(sort) {
      // 活动订单金额
      this.searchParams.sort = sort && sort === 'ascending' ? 0 : 1
      this.searchParams.sort_type = 0
      this.getStudioList()
    }
  }
}
</script>
<style lang="scss" scoped>
.el-cascader {
  min-width: 335px !important;
}
</style>
