<!--
 * @Author: liuzhenlin 461480418@qq.ocm
 * @Date: 2023-01-12 11:57:48
 * @LastEditors: liuzhenlin
 * @LastEditTime: 2023-01-30 16:43:05
 * @Description: file content
 * @FilePath: \crm\pages\customer\add.vue
-->
<template>
  <view class="home">
    <view class="nav">
      <view :style="{ paddingTop }">
        <view class="title" :style="[{ height }, { lineHeight: height }]">
          <view class="back" @click="goBack()">
            <u-icon name="arrow-left" color="#ffffff" size="22"></u-icon>
          </view>
          <text>新增客户</text>
        </view>
      </view>
    </view>
    <view class="main">
      <u-form :model="addForm" :rules="rules" ref="addForm" label-width="0">
        <u-form-item prop="name" borderBottom customStyle="padding:40rpx 0 30rpx">
          <view class="form-label flex_l">
            <view class="label-tag"></view>
            客户名称
          </view>
          <u-input
            placeholder="输入客户名称"
            v-model="addForm.name"
            border="none"
            suffixIcon="account"
            suffixIconStyle="color:#CDCDCD"
            clearable
            customStyle="padding: 0 30rpx 0 12rpx"></u-input>
        </u-form-item>
        <u-form-item prop="industry" borderBottom customStyle="padding:40rpx 0 30rpx" @click="showIndustry = true">
          <view class="form-label flex_l">
            <view class="label-tag"></view>
            客户行业
          </view>
          <u-input
            :readonly="true"
            placeholder="请选择客户行业"
            v-model="addForm.industry"
            border="none"
            suffixIcon="arrow-down"
            suffixIconStyle="color:#CDCDCD"
            clearable
            customStyle="padding: 0 30rpx 0 12rpx"></u-input>
        </u-form-item>
        <!-- <u-form-item prop="level" borderBottom customStyle="padding:40rpx 0 30rpx" @click="showLevel = true">
          <view class="form-label flex_l">
            <view class="label-tag"></view>
            客户级别
          </view>
          <u-input
            :readonly="true"
            placeholder="请选择客户级别"
            v-model="addForm.level"
            border="none"
            suffixIcon="arrow-down"
            suffixIconStyle="color:#CDCDCD"
            clearable
            customStyle="padding: 0 30rpx 0 12rpx"></u-input>
        </u-form-item> -->
        <u-form-item prop="source" borderBottom customStyle="padding:40rpx 0 30rpx" @click="showSource = true">
          <view class="form-label flex_l">
            <view class="label-tag"></view>
            客户来源
          </view>
          <u-input
            :readonly="true"
            placeholder="请选择客户来源"
            v-model="addForm.source"
            border="none"
            suffixIcon="arrow-down"
            suffixIconStyle="color:#CDCDCD"
            clearable
            customStyle="padding: 0 30rpx 0 12rpx"></u-input>
        </u-form-item>
        <u-form-item prop="area" borderBottom customStyle="padding:40rpx 0 30rpx" @click="showArea = true">
          <view class="form-label flex_l">
            <view class="label-tag"></view>
            所在地区
          </view>
          <u-input
            :readonly="true"
            placeholder="请选择所在地区"
            v-model="addForm.area"
            border="none"
            suffixIcon="arrow-down"
            suffixIconStyle="color:#CDCDCD"
            clearable
            customStyle="padding: 0 30rpx 0 12rpx"></u-input>
        </u-form-item>
        <u-form-item borderBottom customStyle="padding:40rpx 0 30rpx">
          <view class="form-label flex_l">
            备注
          </view>
          <u-input
            placeholder="输入备注"
            v-model="addForm.remark"
            border="none"
            clearable
            customStyle="padding: 0 30rpx 0 12rpx"></u-input>
        </u-form-item>
      </u-form>
      <view class="save" @click="handleAdd">保存</view>
    </view>
    <!-- 选择客户行业 -->
    <u-picker
      :show="showIndustry"
      :columns="industryColumns"
      keyName="value"
      @cancel="showIndustry = false"
      @confirm="pickIndustry"></u-picker>
    <!-- 选择客户级别 -->
    <!-- <u-picker
      :show="showLevel"
      :columns="levelColumns"
      keyName="value"
      @cancel="showLevel = false"
      @confirm="pickLevel"></u-picker> -->
    <!-- 选择客户来源 -->
    <u-picker
      :show="showSource"
      :columns="sourceColumns"
      keyName="value"
      @cancel="showSource = false"
      @confirm="pickSource"></u-picker>
    <!-- 选择地区 -->
    <u-picker
      :show="showArea"
      @cancel="showArea = false"
      @close="showArea = false"
      :columns="addressColumns"
      @confirm="localConfirm"
      title="请选择所在地"
      keyName="distName"
      itemHeight="80"
      closeOnClickOverlay
      ref="areaPicker"
      @change="changeHandler"
      immediateChange></u-picker>
    <u-notify ref="uNotify"></u-notify>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>
<script>
  import distrApi from '../../api/base/distr'
  import customerApi from '../../api/customer'
  import to from 'await-to-js'

  export default {
    name: 'omsIndex',
    data() {
      return {
        height: '',
        paddingTop: '',
        showIndustry: false, //选择行业
        // showLevel: false, //选择级别
        showSource: false, //选择来源
        showArea: false, //选择地区
        industryColumns: [],
        // levelColumns: [],
        sourceColumns: [],
        areaLoading: false,
        areaColumns: [], //省份数据
        addressColumns: [], //数据数组
        selectLocation: null, //选中的省市区信息
        addForm: {
          name: '', //客户姓名
          industry: '', //行业
          industryId: null,
          // level: '', //级别
          // levelId: null,
          source: '', //来源
          sourceId: null,
          remark: '', //备注
        },
        rules: {
          name: {
            type: 'string',
            required: true,
            message: '请填写客户名称',
            trigger: ['blur'],
          },
          industry: {
            type: 'string',
            required: true,
            message: '请选择客户行业',
            trigger: ['blur', 'change'],
          },
          // level: {
          //   type: 'string',
          //   required: true,
          //   message: '请选择客户级别',
          //   trigger: ['blur', 'change'],
          // },
          source: {
            type: 'string',
            required: true,
            message: '请选择客户来源',
            trigger: ['blur', 'change'],
          },
          area: {
            type: 'string',
            required: true,
            message: '请选择所在地区',
            trigger: ['blur', 'change'],
          },
        },
      }
    },
    created() {
      const navData = uni.getMenuButtonBoundingClientRect()
      this.height = navData.height + 'px'
      this.paddingTop = navData.top + 'px'
    },
    onShow() {
      this.getOptions()
    },
    methods: {
      // 获取字典数据
      getOptions() {
        Promise.all([
          distrApi.getProvinceInfo(), //省市区
          // this.getDicts('cust_level'), //级别
          this.getDicts('cust_idy'), //行业
          this.getDicts('cust_source'), //来源
        ])
          .then(([province, industry, source]) => {
            this.areaColumns = province.data.list || []
            // this.levelColumns = [level.data.values] || []
            this.industryColumns = [industry.data.values] || []
            this.sourceColumns = [source.data.values] || []
            this.initAreaData()
          })
          .catch((err) => console.log(err))
      },
      // 行业选择
      pickIndustry(e) {
        this.addForm.industryId = e.value[0].key
        this.addForm.industry = e.value[0].value
        this.showIndustry = false
      },
      // 级别选择
      // pickLevel(e) {
      //   this.addForm.levelId = e.value[0].key
      //   this.addForm.level = e.value[0].value
      //   this.showLevel = false
      // },
      // 来源选择
      pickSource(e) {
        this.addForm.sourceId = e.value[0].key
        this.addForm.source = e.value[0].value
        this.showSource = false
      },
      // 初始化地区
      initAreaData() {
        let sheng = []
        let shi = []
        let qu = []
        this.areaColumns.forEach((item) => {
          sheng.push({ distName: item.distName, id: item.id })
          // 设置初始化的数据
          if (item.distName == '北京市') {
            item.children.forEach((child) => {
              shi.push({ distName: child.distName, id: child.id })

              if (child.distName == '北京市') {
                child.children.forEach((el) => {
                  qu.push({ distName: el.distName, id: el.id })
                })
              }
            })
          }
        })
        this.addressColumns.push(
          JSON.parse(JSON.stringify(sheng)),
          JSON.parse(JSON.stringify(shi)),
          JSON.parse(JSON.stringify(qu))
        )
      },
      // 选择地区的时候
      changeHandler(e) {
        const {
          columnIndex,
          value,
          values, // values为当前变化列的数组内容
          index,
          // 微信小程序无法将picker实例传出来，只能通过ref操作
          picker = this.$refs.areaPicker,
        } = e
        // 当第一列值发生变化时，变化第二列(后一列)对应的选项
        if (columnIndex === 0) {
          // picker为选择器this实例，变化第二列对应的选项
          this.areaColumns.forEach((item) => {
            if (value[0].distName == item.distName) {
              if (item.children) {
                let shi = []
                let flag = item.children[0].distName
                item.children.forEach((val, ol) => {
                  shi.push({ distName: val.distName, id: val.id })
                  if (shi[0].distName == flag) {
                    //设置默认开关（选择省份后设置默认城市）
                    flag = ''
                    let qu = []
                    val.children.forEach((vol) => {
                      qu.push({ distName: vol.distName, id: vol.id })
                    })
                    picker.setColumnValues(2, qu)
                  }
                })
                picker.setColumnValues(1, shi)
              } else {
                // console.log(item)
                picker.setColumnValues(1, [])
                picker.setColumnValues(2, [])
              }
            }
          })
        }
        //当第二列变化时，第三列对应变化
        if (columnIndex === 1) {
          this.areaColumns.forEach((item) => {
            if (value[0].distName == item.distName) {
              let shi = []
              item.children.forEach((val, ol) => {
                shi.push({ distName: val.distName, id: val.id })
                if (value[1].distName == val.distName) {
                  let qu = []
                  val.children.forEach((vol) => {
                    qu.push({ distName: vol.distName, id: vol.id })
                  })
                  picker.setColumnValues(2, qu)
                }
              })
            }
          })
        }
      },
      // 确认选中的数据
      localConfirm(e) {
        this.selectLocation = e
        this.addForm.area = e.value[1]
          ? e.value[0].distName + e.value[1].distName + e.value[2].distName
          : e.value[0].distName
        this.showArea = false
      },
      handleAdd() {
        this.$refs.addForm
          .validate()
          .then(async () => {
            let params = {
              custName: this.addForm.name,
              custIndustry: this.addForm.industry,
              // custLevel: this.addForm.level,
              custIndustry: this.addForm.industry,
              source: this.addForm.source,
              custLocation: this.addForm.area,
              remark: this.addForm.remark,
              custDistCode: this.selectLocation.value[0].id,
            }
            // console.log(params)
            const [err, res] = await to(customerApi.createCustomer(params))
            if (err) return
            if (res && res.code == 200) {
              this.$refs.uToast.show({
                type: 'success',
                message: '创建成功',
                complete: () => {
                  this.goBack()
                },
              })
            }
          })
          .catch((err) => {
            // console.log(err)
            this.$refs.uNotify.show({
              top: this.height + this.paddingTop + 10,
              type: 'warning',
              message: err[0].message,
              duration: 1000 * 3,
            })
          })
      },
      goBack() {
        uni.navigateBack({
          //关闭当前页面，返回上一页面或多级页面。
          delta: 1,
        })
      },
    },
  }
</script>
<style>
  page {
    background: #f2f3f5;
  }
</style>
<style lang="scss" scoped>
  .home {
    padding-top: 188rpx;

    .nav {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 284rpx;
      background: #3e7ef8;
      .title {
        position: relative;
        text-align: center;
        font-size: 32rpx;
        font-weight: bold;
        color: #ffffff;
        .back {
          position: absolute;
          top: 0;
          bottom: 0;
          margin: auto;
          left: 70rpx;
          display: flex;
        }
      }
    }

    .main {
      position: absolute;
      width: 100%;
      height: calc(100vh - 188rpx);
      background: #ffffff;
      box-shadow: 0 6rpx 19rpx 2rpx rgba(0, 45, 132, 0.15);
      border-radius: 31rpx 31rpx 0 0;
      padding: 0 32rpx;
      overflow: auto;
      padding-bottom: 64rpx;
      .form-label {
        font-size: 32rpx;
        font-weight: bold;
        color: #323232;
        padding-bottom: 18rpx;
        .label-tag {
          width: 15rpx;
          height: 15rpx;
          background:  #ff4d4f;
          border-radius: 50%;
          margin-right: 10rpx;
        }
      }
      .save {
        width: 569rpx;
        height: 92rpx;
        background: #3e7ef8;
        border-radius: 31rpx;
        margin: 116rpx auto 0;
        font-size: 32rpx;
        color: #ffffff;
        text-align: center;
        line-height: 92rpx;
      }
    }
  }
</style>
