<template>
  <!-- 客户档案 -->
  <div>
    <actionBar menuTitle="客户档案" :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm"
      @openModel="openModel" @searchProtocol="searchProtocol"></actionBar>
    <tables :key="Math.random()" :suspension="true" :tableList="tableList" :tableData="tableData"
      @buttonData="buttonData"></tables>
    <!-- 分页 -->
    <div class="paging_bottom" v-if="Total">
      <pagination :total="Total" :currentPage="Pagination.PageIndex" @changeSize="changeSize"
        @changeCurrent="changeCurrent">
      </pagination>
    </div>
    <el-dialog :title="staffTitle" :visible.sync="staffDialogVisible" width="60%" :close-on-click-modal="false"
      @close="closeDialog">
      <forms ref="childRules" :formNewList="formRuleList" :ruleForm="ruleForm" :operationType="operationType"
        labelWidth="120px"></forms>
      <span slot="footer" class="dialog-footer" v-if="operationType != 'logs'">
        <el-button plain @click="staffDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getCustomer,
    getCustomerDetails,
    addCustomer,
    putCustomer,
    delCustomer,
  } from '@/api/record'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import forms from '@/components/forms'
  import {
    employee,
    formRules,
  } from "./pigeonhole.js";
  import {
    urbanArea
  } from '@/assets/js/districtCode'
  import axios from 'axios'
  export default {
    components: {
      actionBar,
      tables,
      pagination,
      forms
    },
    data() {
      return {
        staffTitle: '添加',
        staffDialogVisible: false,
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        operateList: [{
          type: 'add',
          title: '添加',
          icon: 'el-icon-plus',
        }],
        formList: [{
          type: 'input',
          label: '电话',
          field: 'principalPhone',
          placeholder: '电话',
        }, {
          type: 'select',
          label: '类型',
          field: 'type',
          placeholder: '类型',
          options: [{
              label: '商户',
              value: 0,
            },
            {
              label: '私人',
              value: 1,
            },
          ]
        }, {
          type: 'input',
          label: '地址',
          field: 'address',
          placeholder: '地址',
        }],
        searchRuleForm: {
          principalPhone: '',
          type: '',
          address: '',
        },
        tableList: employee(),
        tableData: [],
        Total: 0,
        formRuleList: [],
        operationType: '',
        searchValue: {},
        ruleForm: {
          fileList: [],
        },
        enterpriseId: null,
        confirmLoading: false,
      }
    },
    mounted() {
      const dataList = formRules();
      this.formRuleList = dataList;
      this.getList()
    },
    methods: {
      // 搜索
      searchProtocol(value) {
        this.searchValue = value
        this.getList()
      },
      // 获取商品列表
      getList() {
        var params = {
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          ...this.searchValue
        }
        getCustomer(params).then(res => {
          if (res.code == 200) {
            this.tableData = res.data.list
            this.tableData.forEach((item, index) => {
              if (item.type == 0) {
                item.name = item.shopName
              } else {
                item.name = item.principalName
              }
            })
            this.Total = res.data.count
          }
        })
      },
      openModel(type) {
        this.operationType = type
        if (type == 'add') {
          this.staffTitle = '添加'
        }
        this.staffDialogVisible = true
      },
      // 获取经纬度
      longitudeLatitude(value) {
        var cityArr = urbanArea()
        var city = this.cityScreening(value.city, cityArr)
        var area = this.cityScreening(value.area, cityArr)
        return new Promise((resolve, inject) => {
          axios.get('https://restapi.amap.com/v3/geocode/geo', {
            params: {
              key: 'fcddcc366fd5bd355e35f01b7cce82ef',
              address: city + area + value.address,
            }
          }).then((res) => {
            resolve(res.data.geocodes[0])
          }).catch(() => {
            this.confirmLoading = false
          })
        })
      },
      // 城市筛选
      cityScreening(value, list) {
        function getChildById(parentArray, id) {
          for (let i = 0; i < parentArray.length; i++) {
            if (parentArray[i].value === id) { // 如果当前元素的ID与目标ID相等，则返回该元素
              return parentArray[i];
            } else if (parentArray[i].children && Array.isArray(parentArray[i].children)) { // 判断当前元素是否有子节点且类型为数组
              const result = getChildById(parentArray[i].children, id); // 对子节点进行递归调用
              if (result !== null) { // 若子节点存在结果，则返回该结果
                return result;
              }
            }
          }
          return null; // 没有找到符合条件的元素时返回null
        }
        var name = getChildById(list, value)
        if (name != null) {
          return name.label
        }
      },
      // 弹窗表单添加
      async handleAdd() {
        let flag = this.$refs['childRules'].validateForm();
        if (flag) {
          this.confirmLoading = true
          if (this.operationType == 'add') {
            var params = {
              ...this.ruleForm
            }
            params.city = this.ruleForm.cityRegion[0]
            params.area = this.ruleForm.cityRegion[1]
            var fileImage = this.picture(this.ruleForm.fileList)
            params.addressImg = fileImage
            delete params.cityRegion;
            delete params.fileList;
            let arr = await this.longitudeLatitude(params)
            var propertyName = arr.location.split(",")
            params.lng = Number(propertyName[0])
            params.lat = Number(propertyName[1])
            await addCustomer(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.staffDialogVisible = false
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
          } else if (this.operationType == 'edit') {
            this.editItem()
          }
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      picture(arr) {
        var imgList = JSON.parse(JSON.stringify(arr))
        var imgArr = []
        imgList.forEach((item, index) => {
          var urlil = this.$baseUrl
          item.url = item.url.replace(urlil, "")
          imgArr.push(item.url)
        })
        var imgString = imgArr.join()
        return imgString
      },
      async editItem() {
        var params = {
          id: this.enterpriseId,
          address: this.ruleForm.address,
          area: this.ruleForm.cityRegion[1],
          city: this.ruleForm.cityRegion[0],
          lat: this.ruleForm.lat,
          lng: this.ruleForm.lng,
          name: this.ruleForm.name,
          principalPhone: this.ruleForm.principalPhone,
          type: this.ruleForm.type,
          remark: this.ruleForm.remark,
        }
        if (this.ruleForm.fileList) {
          var fileImage = this.picture(this.ruleForm.fileList)
          params.addressImg = fileImage
        }
        if (params.lng == 0 || params.lat == 0) {
          let arr = await this.longitudeLatitude(params)
          var propertyName = arr.location.split(",")
          params.lng = Number(propertyName[0])
          params.lat = Number(propertyName[1])
        }
        await putCustomer(params).then(res => {
          if (res.code == 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.getList()
          }
          this.confirmLoading = false
          this.staffDialogVisible = false
        }).catch(() => {
          this.confirmLoading = false
        })
      },
      // 删除
      deleteItem(id) {
        this.$confirm('此操作将永久删除该客户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delCustomer({
            id: id,
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.getList()
            }
          })
        }).catch(() => {});
      },
      buttonData(row, type) {
        this.enterpriseId = row.id
        this.operationType = type
        if (type == 'logs') {
          this.formRuleList.forEach((item, index) => {
            item.disabled = true
          })
        }
        if (type == 'edit' || type == 'logs') {
          this.staffDialogVisible = true
          this.staffTitle = '编辑'
          this.ruleForm = JSON.parse(JSON.stringify(row))
          if (row.addressImg) {
            var arr = row.addressImg.split(',')
            var arr3 = []
            arr.forEach((item, index) => {
              var arr1 = {
                url: '',
              }
              arr1.url = this.$baseUrl + item
              arr3.push(arr1)
            })
            this.ruleForm.fileList = arr3
          }
          var arr1 = []
          arr1.push(row.city)
          arr1.push(row.area)
          this.ruleForm.cityRegion = arr1
        } else if (type == 'del') {
          this.deleteItem(row.id)
        }
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      closeDialog() {
        this.ruleForm = {}
        this.formRuleList.forEach((item, index) => {
          item.disabled = false
        })
        this.$refs.childRules.resetCheck();
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
