<template>
  <div>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" v-dialogDrag append-to-body>
      <el-form size="small" ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading"
        label-width="100px">
        <el-collapse v-model="activeNames">
          <!--客户基本信息面板-->
          <el-collapse-item title="客户基本信息" name="1">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户名称" prop="cusName">
                  <el-input v-model="formData.cusName" placeholder="请输入客户名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户类型" prop="typeCode">
                  <el-select v-model="formData.typeCode" placeholder="请选择客户类型">
                    <el-option v-for="dict in this.getDictDatas(DICT_TYPE.DICT_CUS_TYPE)" :key="dict.value"
                      :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item v-if="formData.typeCode !== '03'" label="身份证号" prop="idCard">
                  <el-input v-model="formData.idCard" placeholder="请输入客户身份证号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item v-if="formData.typeCode !== '03'" label="性别" prop="sex">
                  <el-radio-group v-model="formData.sex">
                    <el-radio v-for="dict in sexDictDatas" :key="dict.value" :label="dict.value">
                      {{ dict.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item v-if="formData.typeCode !== '03'" label="生日" prop="birthday">
                  <el-date-picker v-model="formData.birthday" type="date" placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系方式" prop="phoneNumber">
                  <el-input v-model="formData.phoneNumber" placeholder="请输入客户联系方式" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="客户来源" prop="dataFrom">
                  <el-select v-model="formData.dataFrom" placeholder="请选择客户来源">
                    <el-option v-for="dict in this.getDictDatas(DICT_TYPE.DICT_CUS_DATA_FROM)" :key="dict.value"
                      :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="注册方式" prop="inviterType">
                  <el-select v-model="formData.inviterType" placeholder="请选择注册方式">
                    <el-option v-for="dict in this.getDictDatas(DICT_TYPE.DICT_SIGN_TYPE)" :key="dict.value"
                      :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="选择会员" prop="memberLevelId">
                  <el-select v-model="formData.memberLevelId" placeholder="请选择会员">
                    <el-option v-for="(item,index) in levelList" :key="item.id"
                               :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="联系地址" prop="address">
                  <el-input type="textarea" v-model="formData.address" placeholder="请输入客户联系地址" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!--服务内容折叠面板面板-->
          <el-collapse-item v-if="formData.typeCode == '03'" title="服务内容" name="2">
            <el-table :data="formData.itemList" border size="small" style="width: 100%">
              <el-table-column prop="serContent" align="left" width="180">
                <template slot="header">
                  <i style="color: #409EFF;cursor:pointer" class="el-icon-circle-plus-outline" @click="addItem" />
                  服务内容
                </template>
                <template v-slot="scope">
                  <el-select @change="serviceChange(scope.row)" v-model="scope.row.systemCode" placeholder="请选择服务内容">
                    <el-option v-for="dict in serviceList" :key="dict.id" :label="dict.name" :value="dict.id" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="serTimeStart" align="center" label="开始日期">
                <template v-slot="scope">
                  <el-date-picker v-model="scope.row.serTimeStart" type="date" placeholder="选择服务开始日期">
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column prop="serTimeEnd" align="center" label="结束日期">
                <template v-slot="scope">
                  <el-date-picker v-model="scope.row.serTimeEnd" type="date" placeholder="选择服务结束日期">
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column align="center" width="100" label="操作">
                <template v-slot="scope">
                  <el-button v-if="formData.itemList.length > 1" size="mini" type="text" icon="el-icon-delete"
                    @click="deleteItem(scope.$index, formData.itemList)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
          <!--附件-->
          <el-collapse-item v-if="formData.typeCode !== '03'" title="身份证件信息" name="3">
            <el-row>
              <el-col>
                <el-form-item>
                  <ImageUpload v-model="formData.idCardImage" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>

          <el-collapse-item v-if="formData.typeCode == '03'" title="政企客户资料" name="3">
            <el-row>
              <el-col>
                <el-form-item>
                  <FileUpload v-model="formData.idCardImage" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>

        </el-collapse>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getLevelAll} from '@/api/member/level';
import * as CustomerMainApi from '@/api/base/customer';
import { getServicePackageList } from "@/api/system/servicePackage";
import ImageUpload from '@/components/ImageUpload';
import FileUpload from '@/components/FileUpload';
import Editor from '@/components/Editor';
import { getDictDatas, DICT_TYPE } from '@/utils/dict'

export default {
  name: "CustomerMainForm",
  components: {
    ImageUpload,
    Editor,
    FileUpload
  },
  created() {

    },
  mounted() {
    //初始化会员下拉
    getLevelAll().then(
      res => {
        if (res.code==0)
        {
          this.levelList = res.data
        }
        else {
          this.$modal.msgError(res.msg)
        }

      }
    )
  },
  data() {
    return {
      //会员下拉
      levelList:[],
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      //折叠面板默认展开
      activeNames: ['1', '2', '3'],
      //类型
      typeCode: "",
      //企业
      deptCode: undefined,
      //服务套餐列表
      serviceList: [],
      // 表单参数
      formData: {
        memberLevelId: undefined,
        id: undefined,
        userId: undefined,
        typeCode: '01',
        deptCode: undefined,
        cusName: undefined,
        phoneNumber: undefined,
        birthday: undefined,
        address: undefined,
        sex: '1',
        idCard: undefined,
        idCardImage: undefined,
        dataFrom: '08',
        nearDoTime: undefined,
        nearDoContent: undefined,
        inviter: undefined,
        inviterType: '01',
        status: undefined,
        itemList: [
          {
            systemCode: '',
            serContent: '',
            serTimeStart: '',
            serTimeEnd: ''
          }
        ],
      },
      // 表单校验
      formRules: {
        cusName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        typeCode: [
          { required: true, message: '请选择客户类型', trigger: 'change' },
        ],
        phoneNumber: [
          { required: true, message: '请输入客户联系方式', trigger: 'blur' },
        ],
        dataFrom: [
          { required: true, message: '请选择客户来源', trigger: 'change' },
        ],
        inviterType: [
          { required: true, message: '请选择注册方式', trigger: 'change' },
        ],
        memberLevelId:[
          { required: true, message: '请选择会员', trigger: 'change' },
        ],
      },
      // 性别数据字典
      sexDictDatas: getDictDatas(DICT_TYPE.DICT_SYS_USER_SEX),
      cusBusiTypeDictDatas: getDictDatas(DICT_TYPE.DICT_CUS_BUSI_TYPE)
    };
  },
  methods: {
    /**获取服务套餐精简信息*/
    getServiceList() {
      getServicePackageList().then(response => {
        this.serviceList = response.data;
      });
    },
    /**绑定事件*/
    serviceChange(row) {
      this.serviceList.map(item => {
        if (item.id == row.systemCode) {
          row.serContent = item.name
          return
        }
      })
    },
    /**
     * 新增服务内容
     */
    addItem() {
      const item = {
        serContent: '',
        serTimeStart: '',
        serTimeEnd: ''
      }
      this.formData.itemList.push(item)
    },
    /**
     * 移除服务内容
     */
    deleteItem(index, rows) {
      rows.splice(index, 1);
    },

    /** 打开弹窗 */
    async open(id, typeCode) {
      this.dialogVisible = true;
      this.typeCode = typeCode
      this.reset();
      this.getServiceList()
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await CustomerMainApi.getCustomerMain(id);
          this.formData = res.data;
          this.dialogTitle = "修改客户信息";
        } finally {
          this.formLoading = false;
        }
      }
      this.dialogTitle = "新增客户";
    },
    /** 打开弹窗 */
    async openAttn(row) {
      this.dialogVisible = true;
      this.typeCode = '04'
      this.deptCode = row.deptCode
      console.log(row)
      console.log(this.deptCode)
      this.reset();
      this.dialogTitle = row.cusName;
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        //如果客户类型不是政企客户，没有扩展表信息
        if (data.typeCode !== '03') {
          data.itemList = []
        }
        // 修改的提交
        if (data.id) {
          await CustomerMainApi.updateCustomerMain(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await CustomerMainApi.createCustomerMain(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        userId: undefined,
        typeCode: this.typeCode,
        deptCode: this.deptCode,
        cusName: undefined,
        phoneNumber: undefined,
        birthday: undefined,
        address: undefined,
        sex: '1',
        idCard: undefined,
        idCardImage: undefined,
        dataFrom: '08',
        nearDoTime: undefined,
        nearDoContent: undefined,
        inviter: undefined,
        inviterType: '01',
        status: undefined,
        itemList: [
          {
            serContent: '',
            serTimeStart: '',
            serTimeEnd: ''
          }
        ],
      };
      this.resetForm("formRef");
    }
  }
};
</script>
