<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input
        v-model="listQuery.params.name"
        style="width:200px;margin-right:10px"
        class="filter-item"
        placeholder="姓名"
        clearable
      />
      <el-input
        v-model="listQuery.params.phone"
        style="width:200px;margin-right:10px"
        class="filter-item"
        placeholder="手机号"
        clearable
      />
      <el-input
        v-model="listQuery.params.idCard"
        style="width:200px;margin-right:10px"
        class="filter-item"
        placeholder="身份证号"
        clearable
      />
      <el-cascader
        v-model="regionSearchVal"
        class="filter-item"
        style="width:240px"
        :options="regions"
        :props="{ checkStrictly: true }"
        placeholder="行政区域"
        clearable
      />
      <el-checkbox
        v-model="isStaff"
        style="margin-left:10px"
        @change="handleIsStaff"
      >是否是便民工作人员</el-checkbox>

      <el-button
        type="primary"
        style="margin-left:10px"
        @click="handleSearch"
      >搜索</el-button>
    </div>
    <!-- <el-button
      type="primary"
      size="mini"
      style="margin-bottom:20px"
      @click="handleAdd()"
    >新增规则</el-button> -->
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="待添加列表" name="first" />
      <el-tab-pane label="已添加列表" name="second" />
    </el-tabs>
    <el-table v-loading="loading" :data="list" border style="width: 100%">

      <el-table-column prop="name" label="姓名" width="100">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>

      <el-table-column prop="nameZ" label="姓名(藏语)" width="180">
        <template slot-scope="scope">
          {{ scope.row.nameZ }}
        </template>
      </el-table-column>

      <el-table-column prop="phone" label="手机号" width="120">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>

      <el-table-column prop="phone" label="身份证号" width="200">
        <template slot-scope="scope">
          {{ scope.row.idCard }}
        </template>
      </el-table-column>

      <el-table-column prop="phone" label="是否是便民工作人员" width="150">
        <template slot-scope="scope">
          {{ scope.row.isConvenience ? "是" : "否" }}
        </template>
      </el-table-column>

      <el-table-column prop="phone" label="所属行政区域">
        <template slot-scope="scope">
          {{
            scope.row.permanentResidenceRegion +
              (scope.row.permanentResidenceTown
                ? "-" + scope.row.permanentResidenceTown
                : "") +
              (scope.row.permanentResidenceTownShip
                ? "-" + scope.row.permanentResidenceTownShip
                : "")
          }}
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="activeName === 'first'"
            size="mini"
            type="primary"
            round
            style="font-size:14px;padding:10px 20px"
            @click="handleAdd(scope.row, 'add')"
          >添加</el-button>
          <el-button
            v-if="activeName === 'second'"
            size="mini"
            type="primary"
            round
            style="font-size:14px;padding:10px 20px"
            @click="handleAdd(scope.row, 'edit')"
          >编辑</el-button>
          <el-button
            v-if="activeName === 'second'"
            size="mini"
            type="danger"
            round
            style="font-size:14px;padding:10px 20px"
            @click="handleDel(scope.row)"
          >移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="listQuery.lastPageIndex"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog
      class="dialog"
      :title="diaTitle"
      append-to-body
      center
      width="604px"
      :visible.sync="diaVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :close="closeDia"
    >
      <div class="preview-container">
        <el-form
          ref="form"
          label-position="left"
          label-width="150px"
          :rules="rules"
          :model="form"
        >
          <el-form-item label="商户名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="商户名称(藏文)" prop="nameZ">
            <el-input
              v-model="form.nameZ"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="商户图片" prop="images">
            <CutUploadImage :init-url="form.images" multiple @imgupload="UploadCbk" />
          </el-form-item>
          <el-form-item label="商户地址" prop="address">
            <el-input
              v-model="form.address"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="商户地址(藏文)" prop="addressZ">
            <el-input
              v-model="form.addressZ"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="商户介绍" prop="introduce">
            <el-input
              v-model="form.introduce"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="商户介绍(藏文)" prop="introduceZ">
            <el-input
              v-model="form.introduceZ"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="兑换规则" prop="rule">
            <el-input
              v-model="form.rule"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="兑换规则(藏文)" prop="ruleZ">
            <el-input
              v-model="form.ruleZ"
              placeholder="请输入"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="default" @click="closeDia">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import CutUploadImage from '@/components/cutUploadImage'
import { list, speciallyBusinessList, speciallyBusinessSet } from '@/api/speciallyBusiness'
import { getRegions } from '@/api/region'
export default {
  components: { Pagination, CutUploadImage },
  filters: {
    optionsFilter(value, options = []) {
      const findItem = options.find((option) => option.value === value)
      if (findItem) {
        return findItem.label
      }
      return ''
    }
  },
  data() {
    return {
      loading: false,
      total: 0,
      listQuery: {
        lastPageIndex: 1,
        size: 10,
        params: {
          name: undefined,
          phone: undefined,
          idCard: undefined,
          isConvenience: undefined
        }
      },
      list: undefined,

      listMethod: list,
      activeName: 'first',

      diaTitle: '',
      diaVisible: false,
      form: {
        name: undefined,
        nameZ: undefined,
        images: [],
        address: undefined,
        addressZ: undefined,
        introduce: undefined,
        introduceZ: undefined,
        rule: undefined,
        ruleZ: undefined
      },
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'change' }],
        ruleType: [{ required: true, message: '请选择', trigger: 'change' }],
        regionIds: [{ required: true, message: '请选择', trigger: 'change' }],
        all: [{ required: true, message: '请选择', trigger: 'change' }],
        dateRange: [{ required: true, message: '请选择', trigger: 'change' }]
      },

      ruleTypeOptions: [
        {
          label: '长期规则',
          value: 'FINAL'
        },
        {
          label: '临时规则',
          value: 'TEMPORARY'
        }
      ],
      regions: [],

      isStaff: undefined,
      regionSearchVal: undefined
    }
  },
  watch: {
    'listQuery.lastPageIndex': {
      handler(val) {
        this.getList()
      },
      deep: true // true 深度监听
    }
  },
  created() {
    this.getRegions()
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      this.listMethod(this.listQuery).then(res => {
        // console.log(res);
        this.list = res.d.list
        this.total = res.d.total
        this.pageSize = res.d.pageSize
        this.loading = false
        // if (!res.d.lastPageIndex) {
        //   this.listQuery.lastPageIndex;
        // }
      }).catch(() => {
        this.loading = false
      })
    },
    handleClick() {
      const { activeName } = this
      // console.log(activeName)
      switch (activeName) {
        case 'first':
          this.listMethod = list
          break
        default:
          this.listMethod = speciallyBusinessList
      }
      this.listQuery.lastPageIndex = 1
      this.getList()
    },
    getRegions() {
      getRegions().then(res => {
        const tempData = res.d
        const countyArr = [] // 县,1
        tempData.map(county => {
          const countyObj = {
            value: county.root.name,
            label: county.root.name,
            disabled: !county.root.check,
            children: []
          }
          countyArr.push(countyObj)
          county.node.map(town => {
            const townObj = {
              value: town.root.name,
              label: town.root.name,
              disabled: !town.root.check,
              children: []
            }
            countyObj.children.push(townObj)
            town.node.map(country => {
              townObj.children.push({
                value: country.root.name,
                label: country.root.name,
                disabled: !country.root.check
              })
            })
          })
        })
        this.regions = countyArr
      })
    },
    handleAdd(item, type) {
      if (type === 'edit') {
        this.diaTitle = '编辑'
        const tmpItem = JSON.parse(JSON.stringify(item.speciallyBusinessInfo))
        tmpItem.id = item.id
        this.form = tmpItem
      } else if (type === 'add') {
        this.diaTitle = '添加'
        this.form = {
          id: item.id,
          name: undefined,
          nameZ: undefined,
          images: [],
          address: undefined,
          addressZ: undefined,
          introduce: undefined,
          introduceZ: undefined,
          rule: undefined,
          ruleZ: undefined
        }
      }
      this.$nextTick(() => {
        const formEl = this.$refs['form']
        if (formEl) formEl.clearValidate()
        this.diaVisible = true
      })
    },
    submitForm() {
      // console.log(this.form)
      // return
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(this.form))
          speciallyBusinessSet([{
            id: form.id,
            add: true,
            speciallyBusinessInfo: form
          }]).then(() => {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.closeDia()
            this.getList()
          })
        }
      })
    },
    handleDel(item) {
      this.$confirm('是否移除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        speciallyBusinessSet([{
          id: item.id,
          add: false
        }]).then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getList()
        })
      })
    },
    UploadCbk(data) {
      this.form.images = data
    },
    // jumpStaff(item) {
    //   const { name, id } = item
    //   this.$router.push({
    //     path: '/dept/staff',
    //     query: {
    //       name,
    //       id
    //     }
    //   })
    // },
    closeDia() {
      this.diaVisible = false
    },
    handleIsStaff(val) {
      if (val === false) {
        this.listQuery.params.isConvenience === undefined
        const temp = Object.assign({}, this.listQuery)
        temp.params.isConvenience === undefined
        this.listQuery = temp
      }
    },
    handleSearch() {
      this.listQuery.params.isConvenience = this.isStaff ? true : undefined
      if (this.regionSearchVal) {
        switch (this.regionSearchVal.length) {
          case 1:
            this.listQuery.params.PermanentResidenceRegion = this.regionSearchVal[0]
            this.listQuery.params.PermanentResidenceTown = undefined
            this.listQuery.params.PermanentResidenceTownShip = undefined
            break
          case 2:
            this.listQuery.params.PermanentResidenceTown = this.regionSearchVal[1]
            this.listQuery.params.PermanentResidenceRegion = undefined
            this.listQuery.params.PermanentResidenceTownShip = undefined
            break
          case 3:
            this.listQuery.params.PermanentResidenceTownShip = this.regionSearchVal[2]
            this.listQuery.params.PermanentResidenceRegion = undefined
            this.listQuery.params.PermanentResidenceTown = undefined
            break
          default:
            this.listQuery.params.PermanentResidenceRegion = undefined
            this.listQuery.params.PermanentResidenceTown = undefined
            this.listQuery.params.PermanentResidenceTownShip = undefined
            break
        }
      }
      this.getList()
    }
  }
}
</script>

<style></style>
