<template>
  <ContainerTit>
    <span v-if="customerId" slot="pagetit">编辑客户</span>
    <div slot="headr">
      <el-button
        v-if="!customerId"
        :loading="sub_load"
        @click="delPauseSave(1)"
      >
        清除暂存
      </el-button>
      <el-button v-if="!customerId" :loading="sub_load" @click="temData">
        暂存
      </el-button>
      <el-button :loading="sub_load" type="primary" @click="submitBrand">
        保存
      </el-button>
    </div>
    <div class="page-div">
      <el-form
        ref="form"
        :rules="base_rules"
        :model="form"
        size="small"
        :label-width="customerId ? '120px' : '200px'"
      >
        <el-form-item label="客户编码：" prop="code">
          <el-input
            v-model="form.code"
            style="width: 350px"
            disabled
            placeholder="自动生成"
          ></el-input>
        </el-form-item>
        <el-form-item label="客户名称：" prop="name">
          <el-input
            v-model="form.name"
            style="width: 350px"
            placeholder="请填写客户真实姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="登录账号：" prop="mobile">
          <el-input
            v-model="form.mobile"
            :disabled="!!customer_id && !!form.openId"
            style="width: 350px"
            placeholder="请填写客户手机号"
            @blur="moblieChange"
          ></el-input>
          <!--          <el-checkbox v-model="checked">发送验证码</el-checkbox>-->
        </el-form-item>
        <el-form-item label="推荐人：" prop="currentUnit">
          <el-select
            v-model="form.recommenderType"
            placeholder="请选择"
            style="width: 85px"
            @change="btypeChange"
          >
            <el-option
              v-for="item in options_list"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <SelectCustomer
            v-if="form.recommenderType === 3"
            v-model="currentUnit"
            :modal="!customerId"
            :clearable="false"
            width="235"
            @change="customerSel"
          />
          <el-input
            v-if="form.recommenderType === 2"
            v-model="currentUnit"
            clearable
            style="width: 265px"
            placeholder="请选择员工"
            @clear="staff = ''"
            @blur="staff = ''"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="saleFn(true)"
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item label="账号状态：" prop="enableStatus">
          <el-radio v-model="form.enableStatus" :label="5">启用</el-radio>
          <el-radio v-model="form.enableStatus" :label="4">禁用</el-radio>
        </el-form-item>

        <el-form-item label="客户类型：" prop="type">
          <el-select
            v-model="form.type"
            style="width: 350px"
            placeholder="客户类型"
            @change="typeChange"
          >
            <el-option
              v-for="item in customerType"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button
            v-if="systemType === 1"
            type="text"
            size="mini"
            @click="getAllCustomerSource"
          >
            【刷新】
          </el-button>
          <el-button
            v-if="systemType === 1"
            type="text"
            size="mini"
            @click="show_model = true"
          >
            【新建类型】
          </el-button>
        </el-form-item>
        <el-form-item
          label="联系人："
          style="margin-bottom: 20px"
          prop="contactName"
        >
          <el-input
            v-model="form.contact.name"
            placeholder="请输入客户联系人"
            style="width: 350px"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="联系人电话："
          style="margin-bottom: 20px"
          prop="contactMobile"
        >
          <el-input
            v-model="form.contact.mobile"
            placeholder="请输入客户联系人电话"
            style="width: 350px"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="联系人地区："
          prop="contact"
          style="margin-bottom: 20px"
        >
          <span v-if="customer_id">
            <RegionSelect
              v-if="region.length"
              v-model="region"
              size="medium"
              style="margin-bottom: 10px; width: 350px"
              @change="contactChange"
            />
          </span>
          <span v-else>
            <RegionSelect
              v-model="region"
              size="medium"
              style="margin-bottom: 10px; width: 350px"
              @change="contactChange"
            />
          </span>
        </el-form-item>
        <el-form-item label="详细地址：" prop="contactAddress">
          <el-input
            v-model="form.contact.address"
            placeholder="例如楼牌，门号"
            style="width: 350px"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="systemType === 1" label="商铺：">
          <SelectShop
            v-model="form.shopId"
            :width="350"
            :clearable="true"
            :is-default="true"
            @clear="shopClear"
            @default="shopDefault"
          />
          <el-button size="mini" type="text" @click="goShop(1)">
            【新建商铺】
          </el-button>
        </el-form-item>
        <el-form-item label="销售部门：" style="margin-bottom: 20px">
          <el-tag v-if="department_name && !!customerId" type="success">
            {{ department_name }}
          </el-tag>
          <span style="display: inline-block">
            <DepartmentSel
              v-model="departmentId"
              :width="350"
              :placeholder="department_name"
              size="small"
              :is-show-add="true"
              @change="selBranch"
            />
          </span>
          <el-button
            v-if="systemType === 1"
            size="mini"
            type="text"
            @click="add_department = true"
          >
            【新建部门】
          </el-button>
        </el-form-item>
        <el-form-item
          label="业务员："
          prop="salesManId"
          style="margin-bottom: 20px"
        >
          <el-select
            v-model="form.salesManId"
            style="width: 350px"
            filterable
            placeholder="业务员"
            @change="staffChange"
          >
            <el-option
              v-for="(item, index) in staff_list"
              :key="index"
              :label="item.staffName"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button size="mini" type="text" @click="getAllStaff">
            【刷新】
          </el-button>
          <el-button size="mini" type="text" @click="add_staff = true">
            【新建员工】
          </el-button>
        </el-form-item>
        <el-form-item label="营业执照：">
          <UploadQiniu
            :file-list="img_list"
            :modal="!customerId"
            @uploadSuccess="uploadSuccess"
            @handleRemove="uploadRemove"
          />
        </el-form-item>
        <el-form-item
          label="客户生日："
          prop="birthday"
          style="margin-bottom: 20px"
        >
          <el-date-picker
            v-model="form.birthday"
            style="width: 350px"
            default-value="1990-01-01"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="timestamp"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          label="客户备注："
          prop="remark"
          style="margin-bottom: 20px"
        >
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入您需要的服务"
            style="width: 350px"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="分拣区：" prop="" style="margin-bottom: 20px">
          <el-select
            v-model="form.reservoirId"
            style="width: 350px"
            filterable
            placeholder="分拣区"
          >
            <el-option
              v-for="(item, index) in area_list"
              :key="index"
              :label="item.reservoirName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>-->
      </el-form>
    </div>

    <!--    新建员工-->
    <AddStaff
      v-if="add_staff"
      :modal="!customerId"
      :visible="add_staff"
      @close="add_staff = false"
      @goShop="goShop"
    ></AddStaff>
    <!--    新增部门-->
    <AddDepartment
      v-if="add_department"
      :modal="!customerId"
      :visible="add_department"
      @close="add_department = false"
    ></AddDepartment>

    <!--    新建客户类型-->
    <CutomerTypeAdd
      :modal="!customerId"
      :is-show="show_model"
      @cancel="show_model = false"
    ></CutomerTypeAdd>
    <staffListModal
      v-if="staff_show"
      :modal="!customerId"
      :is-show="staff_show"
      :is-check="false"
      :isserch="isserch"
      @cancel="staff_show = false"
      @confirm="staffSel"
    />
  </ContainerTit>
</template>

<script>
  import RegionSelect from "@/component/common/RegionSelectJSON";
  import DepartmentSel from "@/component/common/DepartmentSel.vue";
  // 新增部门
  import AddDepartment from "@/component/SystemSettings/AddDepartment.vue";
  // 新建员工
  import AddStaff from "@/component/SystemSettings/AddStaff.vue";
  import CutomerTypeAdd from "@/component/customer/CutomerTypeAdd";
  // 上传照片
  import UploadQiniu from "@/component/common/UploadQiniu.vue";
  import SelectShop from "@/component/goods/SelectShop.vue";
  import {
    addCustomerSource,
    editCustomerSource,
    getCustomerSourceList,
  } from "@/api/System";
  import { getCustomerInfo, addCustomer, editCustomer } from "@/api/Customer";
  import { getAllStaff } from "@/api/Department";
  import { addPauseSave, delPauseSave, getPauseSave } from "@/api/common";
  import { mapGetters } from "vuex";
  import { getListReservoir } from "@/api/Stock";
  import SelectCustomer from "@/component/common/SelectCustomer.vue";
  import staffListModal from "@/component/common/staffListModal";

  export default {
    name: "AddCustomer",
    components: {
      CutomerTypeAdd,
      RegionSelect,
      SelectShop,
      DepartmentSel,
      UploadQiniu,
      AddDepartment, // 新增部门
      AddStaff, // 新增员工
      SelectCustomer,
      staffListModal,
    },
    props: {
      customerId: {
        type: [Number, String],
        default: 0,
      },
    },
    data() {
      const validateName = (rule, value, callback) => {
        const re = /^1[3456789]\d{9}$/; // 正则表达式
        if (value === "") {
          callback(new Error());
        } else if (!re.test(value)) {
          callback(new Error("手机号格式有误，请重新输入!"));
        } else {
          callback();
        }
      };
      return {
        img_list: [], // 营业执照
        regionName: "",
        sub_load: false,
        show_model: false, // 是否打开新建类型
        add_department: false, // 新增部门
        add_staff: false, // 新增员工
        customer_id: "",
        department_name: "请选择销售部门",
        show_shop: false,
        saleMan_list: [],
        region: [],
        customerRegion: [],
        base_rules: {
          mobile: [
            { required: true, message: "请填写客户手机号", trigger: "blur" },
            { validator: validateName, trigger: "blur" },
          ],
          name: [
            { required: true, message: "客户名称不能为空", trigger: "blur" },
          ],
        },
        customerType: [],
        department_list: [],
        departmentPidPath: [],
        staff_list: [],
        departmentId: [],
        contactName: [],
        checked: false,
        contactregion: "",
        typeName: "",
        pageName: "",
        form: {
          tempSave: "",
          latitude: "",
          longitude: "",
          password: "",
          area: "",
          // 'status': '1', // 审核状态
          mobile: "",
          enableStatus: 5, // 启用状态
          name: "",
          code: "",
          type: "",
          provinceCode: "",
          cityCode: "",
          districtCode: "",
          address: "",
          managerMobile: "",
          shopId: "", // 商铺的id
          departmentId: "", // 部门的id
          salesManId: "",
          salesManCode: "",
          salesManName: "",
          birthday: "",
          remark: "",
          reservoirId: "",
          recommenderType: 3,
          recommenderId: "",
          extend: {
            license: "",
          },
          contact: {
            area: "",
            name: "",
            mobile: "",
            provinceCode: "",
            cityCode: "",
            districtCode: "",
            address: "",
          },
        },
        isEvidence: 4, // 是否需要上传营业制造
        brand: "",
        area_list: [], //库位
        options_list: [
          { label: "客户", value: 3 },
          { label: "员工", value: 2 },
        ],
        currentUnit: "",
        staff_show: false,
        isserch: true,
      };
    },
    computed: {
      ...mapGetters({
        systemType: "MUser/systemType",
        storeData: "MUser/storeData",
      }),
    },
    async created() {
      this.pageName = this.$route.name;
      this.brand = this.$route.path.includes("brand");
      await this.getAllCustomerSource();
      await this.getAllStaff();
      // await this.getListReservoir();
      if (this.$route.params.id || this.customerId) {
        this.customer_id = this.$route.params.id || this.customerId;
        await this.getCustomerInfo();
      } else {
        if ([2, 3].includes(this.systemType)) {
          this.form.shopId = this.storeData.id;
        }
        await this.getTempCustomerData();
      }
    },
    methods: {
      // 库位
      /* async getListReservoir() {
        const data = await getListReservoir({ type: 8 });
        this.area_list = data.data;
      },*/
      typeChange(val) {
        const data = this.customerType.find((item) => item.id === val);
        if (data) {
          this.isEvidence = data.isEvidence;
        }
      },
      // 同步电话
      moblieChange() {
        this.form.contact.mobile = this.form.mobile;
      },
      // 上传营业执照
      uploadSuccess(val, res, file, fileList) {
        this.form.extend.license = val;
        this.img_list = fileList;
      },
      uploadRemove(file, fileList) {
        this.form.extend.license = "";
        this.img_list = fileList;
      },
      // 客户删除
      shopClear() {
        this.form.shopId = "";
      },
      // 新增客户类型
      async addData() {
        this.$refs.add_form.validate(async (valid) => {
          if (valid) {
            let target = {};
            if (!this.is_edit) {
              target = await addCustomerSource({
                ...this.add_form,
              });
            } else {
              target = await editCustomerSource(this.type_id, {
                ...this.add_form,
              });
            }
            const data = target;

            this.$message("客户类型创建成功");
            this.show_model = false;
          }
        });
      },
      //  获取客户类型
      async getAllCustomerSource() {
        const data = await getCustomerSourceList();
        if (data.data.length) {
          this.customerType = data.data;
          const defaultData = data.data.find(
            (item) => item.defaultStatus === 5
          );
          if (defaultData) {
            this.form.type = defaultData.id;
          } else {
            this.form.type = data.data[0].id;
          }
        } else {
          this.customerType = [];
        }
      },

      searchcomplete(res) {
        if (!res || !res.Ir || !res.Ir[0]) return;
        const points = res.Ir[0].point;
        this.form.latitude = points.lat;
        this.form.longitude = points.lng;
      },
      mapClick({ type, target, point, pixel, overlay }) {
        this.form.latitude = point.lat;
        this.form.longitude = point.lng;
        if (overlay.z.title) {
          this.form.address = overlay.z.title;
        }
      },
      // 获取员工列表
      async getAllStaff() {
        const { data } = await getAllStaff({
          departmentId: this.form.departmentId,
          page: "1",
          pageSize: "999",
        });

        this.staff_list = data;
      },
      // 选择员工
      staffChange(val) {
        const target = this.staff_list.find((item) => item.id === val);
        this.form.salesManCode = target.staffCode;
        this.form.salesManName = target.staffName;
      },
      // 选择部门
      selBranch(val) {
        this.form.departmentId = val[val.length - 1];
        this.departmentPidPath = val.join(",");
        this.form.salesManId = "";
        this.form.salesManCode = "";
        this.form.salesManName = "";
        this.getAllStaff();
      },
      //  联系人选择地址
      contactChange(val, params) {
        const provinceName = params[0].label;
        const cityName = params[1] ? params[1].label : "";
        const districtName = params[2] ? params[2].label : "";
        this.contactName = {
          provinceName: provinceName,
          cityName: cityName,
          districtName: districtName,
        };
        this.contactregion = provinceName + cityName + districtName;
        this.form.contact.provinceCode = val[0];
        this.form.contact.cityCode = val[1] || "";
        this.form.contact.districtCode = val[2] || "";
        // province
        this.form.provinceCode = val[0];
        this.form.cityCode = val[1];
        this.form.districtCode = val[2];
      },
      // 客户选择区域
      regionChange(val, params) {
        const provinceName = params[0].label;
        const cityName = params[1] ? params[1].label : "";
        const districtName = params[2] ? params[2].label : "";
        this.regionName =
          provinceName + cityName + districtName + this.form.address;
        this.form.provinceCode = val[0];
        this.form.cityCode = val[1] || "";
        this.form.districtCode = val[2] || "";
      },
      getRegion(province, city, district) {
        this.regionName =
          province.name +
          (city.name || "") +
          (district.name || "") +
          this.form.address;
      },
      // 暂存数据
      async temData() {
        const params = {
          ...this.form,
          birthday: parseInt(this.form.birthday / 1000),
        };
        if (this.form.contact.id) {
          params.contact.id = this.form.contact.id;
        }
        this.sub_load = true;
        try {
          const data = await addPauseSave({
            key: this.pageName,
            data: params,
          });
          this.sub_load = false;

          this.$message({
            message: "暂存成功",
            type: "success",
          });
          if (this.systemType === 2) {
            this.$closeCurrentGoEdit("/SingleStore/Customer/StoreCustomer");
          } else {
            this.$closeCurrentGoEdit("/Customer/CustomerAdmin/CustomerList");
          }
        } catch (e) {
          this.sub_load = false;
        }
      },
      // 清除暂存
      async delPauseSave(type) {
        const data = delPauseSave({
          key: this.pageName,
        });

        if (type) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
          this.$closeCurrentGoEdit("/Customer/CustomerAdmin/AddCustomer");
        }
      },
      // 新建客户  addCustomer
      async submitBrand() {
        if (!this.form.name.trim()) {
          this.$message.warning("客户名称不能为空");
          return;
        }
        if (!this.form.type) {
          this.$message.warning("客户类型不能为空");
          return;
        }
        if (this.isEvidence === 5 && !this.form.extend.license) {
          this.$message(
            "由于您选择的客户类型是零售商或者是批发商，所以必须上传营业执照"
          );
          return;
        }
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            const params = {
              ...this.form,
              managerMobile: this.form.contact.mobile,
              birthday: parseInt(this.form.birthday / 1000),
            };
            if (this.form.contact.id) {
              params.contact.id = this.form.contact.id;
            }
            this.sub_load = true;
            try {
              let target = {};
              if (this.customer_id) {
                target = await editCustomer(this.customer_id, {
                  ...params,
                });
              } else {
                target = await addCustomer(params);
              }
              this.sub_load = false;

              this.$message({
                message: "提交成功",
                type: "success",
              });
              if (this.customer_id) {
                this.$emit("subSuccess");
              } else {
                this.delPauseSave();
                if (this.systemType === 2) {
                  this.$closeCurrentGoEdit(
                    "/SingleStore/Customer/StoreCustomer"
                  );
                } else {
                  this.$closeCurrentGoEdit(
                    "/Customer/CustomerAdmin/CustomerList"
                  );
                }
              }
            } catch (e) {
              this.sub_load = false;
            }
          }
        });
      },
      shopDefault(val) {
        if (!this.customerId) {
          this.form.shopId = val;
        }
      },
      //  客户详情 getCustomerInfo
      async getCustomerInfo() {
        const { data } = await getCustomerInfo(this.customer_id);

        // 默认客户类型
        const defaultType = this.customerType.find(
          (item) => item.defaultStatus === 5
        );
        const extend =
          data.extend && data.extend.license
            ? data.extend
            : {
                license: "",
              };
        this.form = {
          ...data,
          type: data.type || (defaultType ? defaultType.id : data.type),
          birthday: data.birthday * 1000,
          contact: data.contact[0],
          extend: extend,
        };
        this.customerRegion = [
          data.provinceCode || 0,
          data.cityCode || 0,
          data.districtCode || 0,
        ].map((item) => {
          return parseInt(item);
        });
        this.region = [
          data.contact[0].provinceCode,
          data.contact[0].cityCode,
          data.contact[0].districtCode,
        ].map((item) => {
          return parseInt(item);
        });
        this.department_name = data.departmentName;
        if (data.extend && data.extend.license) {
          this.img_list = [
            {
              url: data.extend.license,
              name: "",
            },
          ];
        }
        this.currentUnit = data.recommenderName;
      },
      // 获取暂存
      async getTempCustomerData() {
        const { data } = await getPauseSave({
          key: this.pageName,
        });

        if (JSON.stringify(data) === "{}") return;
        this.form = {
          ...data,
          birthday: data.birthday * 1000,
          contact: data.contact,
        };
        this.customerRegion = [
          data.provinceCode || 0,
          data.cityCode || 0,
          data.districtCode || 0,
        ].map((item) => {
          return parseInt(item);
        });
        this.region = [
          data.contact.provinceCode,
          data.contact.cityCode,
          data.contact.districtCode,
        ].map((item) => {
          return parseInt(item);
        });
        this.department_name = data.departmentName;
      },
      goShop(tag) {
        if (tag === 1) {
          this.$router.push("/SystemSettings/liansuoguanli/AddShop");
        }
        this.$emit("goShop");
      },
      btypeChange() {
        this.currentUnit = "";
      },
      customerSel(val, row) {
        this.form.recommenderId = row[0].id;
      },
      saleFn(isserch) {
        this.staff_show = true;
        this.isserch = isserch;
      },
      // 选择员工
      staffSel(val) {
        const row = val[0];
        this.currentUnit = row.staffName;
        this.form.recommenderId = row.id;
      },
    },
  };
</script>
<style scoped>
  .creat-shop {
    color: #1890ff;
    font-size: 12px;
  }
</style>
