
<template>
  <div>
    <el-button type="primary"
               plain
               icon="el-icon-circle-plus-outline"
               style="margin-bottom:10px;"
               @click="toStep(2)">新增</el-button>
    <el-card shadow="never"
             class="aui-card--fill">
      <el-table v-loading="dataListLoading"
                :data="dataList"
                border
                style="width: 100%;"
                @row-contextmenu="handleRowContext"
                @cell-dblclick="handleRowContext">
        <el-table-column prop="logo"
                         label="客户LOGO"
                         header-align="left"
                         align="left"
                         width="100">
          <template slot-scope="scope">
            <el-image v-if="scope.row.logo"
                      style="width: 40px; height: 40px;text-align: center;"
                      :src="scope.row.logo"
                      :preview-src-list="[scope.row.logo]">
            </el-image>
            <!-- <img v-if="scope.row.logo" :src="scope.row.logo" class="customer-logo"  /> -->
          </template>
        </el-table-column>
        <el-table-column prop="customerName"
                         label="客户名称"
                         header-align="left"
                         align="left"
                         width="300"></el-table-column>
        <el-table-column label="操作"
                         fixed="right"
                         header-align="right"
                         align="right">
          <template slot-scope="scope">
            <el-button size="small"
                       v-if="!scope.row.hasRootAgency"
                       @click="toSetUpStep(scope.row.customerId, 3)">根级组织设置</el-button>
            <el-button size="small"
                       v-if="!scope.row.hasManager"
                       @click="toSetUpStep(scope.row.customerId, 4)">管理员设置</el-button>
            <el-button size="small"
                       @click="onOpenDetails(scope.row.customerId)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog @close="toStep(0)"
               width="850px"
               :visible.sync="centerDialogVisible"
               center
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <div v-if="step == 1">
        <componentInfo :dataList="details"></componentInfo>
      </div>
      <div class="add-c-box"
           v-if="step == 2">
        <h2>客户信息</h2>
        <el-form label-position="left"
                 label-width="80px"
                 :model="dataForm2"
                 :rules="dataRule"
                 ref="dataForm"
                 @keyup.enter.native="submitStepHandle()"
                 status-icon>
          <el-form-item prop="customerName"
                        label="客户名称">
            <el-input v-model="dataForm2.customerName"
                      key="customerName">
              <span slot="prefix"
                    class="el-input__icon">
                <svg class="icon-svg"
                     aria-hidden="true">
                  <use xlink:href="#icon-user"></use>
                </svg>
              </span>
            </el-input>
          </el-form-item>
          <el-form-item prop="organizationLevel"
                        label="组织级别">
            <el-select v-model="dataForm2.organizationLevel"
                       key="organizationLevel">
              <el-option v-for="(val, key) in organizationLevels"
                         :key="key"
                         :label="key"
                         :value="val"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="logo"
                        label="客户LOGO">
            <el-upload class="avatar-uploader"
                       :action="uploadUlr"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccess">
              <img v-if="dataForm2.logo"
                   :src="dataForm2.logo"
                   class="avatar" />
              <i v-else
                 class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-button type="primary"
                     @click="submitStepHandle">下一步</el-button>
        </el-form>
      </div>
      <div class="add-c-box"
           v-else-if="step == 3">
        <h2>根级组织信息</h2>
        <el-form label-position="left"
                 label-width="80px"
                 :model="dataForm3"
                 :rules="dataRule"
                 ref="dataForm"
                 @keyup.enter.native="submitStepHandle()"
                 status-icon>
          <el-form-item prop="agencyName"
                        label="组织名称">
            <el-input v-model="dataForm3.agencyName"
                      key="agencyName">
              <span slot="prefix"
                    class="el-input__icon">
                <svg class="icon-svg"
                     aria-hidden="true">
                  <use xlink:href="#icon-user"></use>
                </svg>
              </span>
            </el-input>
          </el-form-item>
          <el-form-item prop="level"
                        label="组织级别">
            <el-select v-model="dataForm3.level"
                       key="level"
                       @change="onLevelChange">
              <el-option v-for="(val, key) in organizationLevels"
                         :key="key"
                         :label="key"
                         :value="val"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :prop="pcd"
                        label="选择地区"
                        :show-message="pcdError">
            <v-distpicker :hideArea="isHideArea"
                          :province="dataForm3.province"
                          :city="dataForm3.city"
                          :area="dataForm3.district"
                          :onlyProvince="isOnlyProvince"
                          @province="onChangeProvince"
                          @city="onChangeCity"
                          @area="onChangeArea"></v-distpicker>
          </el-form-item>
          <el-form-item prop="areaCode"
                        label="地区编码">
            <el-input v-model="dataForm3.areaCode"
                      key="areaCode"
                      disabled></el-input>
          </el-form-item>
          <el-button type="primary"
                     @click="submitStepHandle">下一步</el-button>
        </el-form>
      </div>
      <div class="add-c-box"
           v-else-if="step == 4">
        <h2>管理员信息</h2>
        <el-form label-position="left"
                 label-width="80px"
                 :model="dataForm4"
                 :rules="dataRule"
                 ref="dataForm"
                 @keyup.enter.native="submitStepHandle()"
                 status-icon>
          <el-form-item prop="realName"
                        label="姓名">
            <el-input v-model="dataForm4.realName"
                      key="realName">
              <span slot="prefix"
                    class="el-input__icon">
                <svg class="icon-svg"
                     aria-hidden="true">
                  <use xlink:href="#icon-user"></use>
                </svg>
              </span>
            </el-input>
          </el-form-item>
          <el-form-item prop="gender"
                        label="性别">
            <el-select v-model="dataForm4.gender"
                       key="gender">
              <el-option v-for="(val, key) in genders"
                         :key="key"
                         :label="val"
                         :value="key"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="mobile"
                        label="手机号">
            <el-input v-model.number="dataForm4.mobile"
                      key="mobile">
              <span slot="prefix"
                    class="el-input__icon">
                <svg class="icon-svg"
                     aria-hidden="true">
                  <use xlink:href="#icon-user"></use>
                </svg>
              </span>
            </el-input>
          </el-form-item>
          <el-button type="primary"
                     @click="submitStepHandle">完成</el-button>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<style
  lang="scss"
  src="@/assets/scss/modules/c-manage/customer-manage.scss"
></style>

<script>

import mixinViewModule from '@/mixins/view-module'
import VDistpicker from 'v-distpicker'
import { Loading } from 'element-ui'
import componentInfo from './customer-info'

export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '/oper/crm/customer/getvalidcustomerlist',
        getDataListIsPage: false
      },
      uploadUlr: window.SITE_CONFIG['apiURL'] + '/oss/file/customerlogo/upload',
      pcd: 'district',
      pcdError: true,
      centerDialogVisible: false,
      organizationLevels: {
        社区级: 'community',
        '乡（镇、街道）级': 'street',
        区县级: 'district',
        市级: 'city',
        省级: 'province'
      },
      genders: ['未知', '男', '女'],
      step: 1,
      details: [],
      customerId: '',
      agencyId: '',
      dataForm2: {
        logo: '',
        customerName: '',
        organizationLevel: ''
      },
      dataForm3: {
        customerId: '',
        agencyName: '',
        level: '',
        areaCode: '',
        province: '',
        city: '',
        district: ''
      },
      dataForm4: {
        customerId: '',
        realName: '',
        gender: '',
        mobile: '',
        agencyId: ''
      },
      isHideArea: false,
      isOnlyProvince: false,
      checkMobile: (rule, value, callback) => {
        // if (!Number.isInteger(value)) {
        //   return callback(new Error('手机号格式不正确'))
        // }
        var phoneReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
        if (!phoneReg.test(value.toString())) {
          return callback(new Error('请输入正确格式的手机号'))
        }
        callback()
      }
    }
  },
  components: {
    VDistpicker,
    componentInfo
  },
  mounted () {
    // console.log(app.ajax)
  },
  methods: {
    toStep (s) {
      this.step = s
      if (s !== 0) {
        this.centerDialogVisible = true
      }
    },
    toSetUpStep (customerId, step) {
      this.customerId = customerId
      this.toStep(step)
    },
    getCustomerDetail (id) {
      const url = '/oper/crm/customer/detail'
      this.$http
        .post(url, { customerId: id })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('获取详情成功')
            this.details = res.data
            console.log(res.data)
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    async onOpenDetails (customerId) {
      let loadingInstance = Loading.service()
      await this.getCustomerDetail(customerId)
      this.toStep(1)
      loadingInstance.close()
    },
    submitDataForm2 () {
      console.log(this.dataForm2)
      const url = '/oper/crm/customer/add'
      const dataForm = this.dataForm2
      return this.$http
        .post(url, dataForm)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.customerId = res.data.customerId
            console.log('提交信息成功' + this.step)
            this.toStep(3)
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    submitDataForm3 () {
      this.dataForm3.customerId = this.customerId
      console.log(this.dataForm3)
      const url = '/oper/crm/customer/addrootagency'
      const dataForm = this.dataForm3
      return this.$http
        .post(url, dataForm)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.agencyId = res.data.agencyId
            console.log('提交信息成功' + this.step)
            this.toStep(4)
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    submitDataForm4 () {
      let dataForm = this.dataForm4
      dataForm.customerId = this.customerId
      dataForm.agencyId = this.dataForm4.agencyId
      dataForm.mobile = this.dataForm4.mobile.toString()
      console.log(dataForm)
      const url = '/oper/crm/customer/addmanager'

      window.app.ajax.post(url, dataForm,
        (data, rspMsg) => {
          this.$message.success('提交信息成功' + this.step)
          this.toStep(0)
        },
        (rspMsg, data) => {
          this.$message.error(rspMsg)
        })

      // return this.$http
      //   .post(url, dataForm)
      //   .then(({ data: res }) => {
      //     if (res.code !== 0) {
      //       return this.$message.error(res.msg)
      //     } else {
      //       console.log('提交信息成功' + this.step)
      //       this.toStep(0)
      //     }
      //   })
      //   .catch(() => {
      //     return this.$message.error('网络错误')
      //   })
    },
    async toNextStep () {
      let loadingInstance = Loading.service()
      if (this.step === 2) {
        await this.submitDataForm2()
      } else if (this.step === 3) {
        await this.submitDataForm3()
      } else if (this.step === 4) {
        await this.submitDataForm4()
      }
      loadingInstance.close()
    },
    submitStepHandle () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.toNextStep()
      })
    },
    // 改变组织级别
    onLevelChange (e) {
      this.dataForm3.province = ''
      this.dataForm3.city = ''
      this.dataForm3.district = ''
    },
    onChangeProvince (e) {
      this.dataForm3.areaCode = e.code
      this.dataForm3.province = e.value
      this.dataForm3.city = ''
      this.dataForm3.district = ''
      if (this.pcd === 'province') {
        this.pcdError = false
      }
    },
    onChangeCity (e) {
      this.dataForm3.areaCode = e.code
      this.dataForm3.city = e.value
      this.dataForm3.district = ''
      if (this.pcd === 'city') {
        this.pcdError = false
      }
    },
    onChangeArea (e) {
      this.dataForm3.areaCode = e.code
      this.dataForm3.district = e.value
      if (this.pcd === 'district') {
        this.pcdError = false
      }
    },
    handleAvatarSuccess (res, file) {
      if (res.code === 0 && res.msg === 'success') {
        this.dataForm2.logo = res.data.url
      } else this.$message.error(res.msg)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleCellDbclick (row, column, cell, event) {
      if (column.label === '客户LOGO') {
        this.copy(row.logo)
      }
    },
    handleRowContext (row, column, event) {
      this.copy(row.logo)
    },
    copy (data) {
      let url = data
      let oInput = document.createElement('input')
      oInput.value = url
      document.body.appendChild(oInput)
      oInput.select()
      console.log(oInput.value)
      document.execCommand('Copy')
      this.$message({
        message: 'LOGO链接复制成功',
        type: 'success'
      })
      oInput.remove()
    }
  },
  computed: {
    dataRule () {
      return {
        customerName: [{ required: true, message: '请输入客户名称' }],
        organizationLevel: [{ required: true, message: '请选择组织级别' }],
        agencyName: [{ required: true, message: '请输入组织名称' }],
        level: [{ required: true, message: '请选择组织级别' }],
        areaCode: [{ required: true, message: '请输入地区编码' }],
        province: [{ required: true, message: '请选择省份', trigger: 'blur' }],
        city: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        district: [{ required: true, message: '请选择区县', trigger: 'blur' }],
        realName: [{ required: true, message: '请输入姓名' }],
        gender: [{ required: true, message: '请输入性别' }],
        mobile: [
          { required: true, message: '请输入手机号' },
          { validator: this.checkMobile }
        ]
      }
    }
  },
  watch: {
    step (nVal, oVal) {
      if (nVal === 0) {
        this.dataForm2 = {
          customerName: '',
          organizationLevel: ''
        }
        this.dataForm3 = {
          agencyName: '',
          level: '',
          areaCode: '',
          province: '',
          city: '',
          district: ''
        }
        this.dataForm4 = {
          realName: '',
          gender: '',
          mobile: ''
        }
        this.centerDialogVisible = false
        if (oVal === 3 || oVal === 4) {
          this.query()
        }
      }
    },
    'dataForm3.level': (nVal) => {
      this.pcdError = true
      this.dataForm3.areaCode = ''
      if (nVal === 'province') {
        this.isOnlyProvince = true
        this.pcd = 'province'
      } else if (nVal === 'city') {
        this.isHideArea = true
        this.isOnlyProvince = false
        this.pcd = 'city'
      } else {
        this.pcd = 'district'
        this.isHideArea = false
        this.isOnlyProvince = false
      }
      if (nVal !== '') {
        this.$nextTick(() => {
          this.$refs['dataForm'].validate((valid) => {
            if (!valid) {
              return false
            }
          })
        })
      }
    }
  }
}
</script>
