<template>
  <div class="app-container">
    <div>{{ editPage ? '修改' : '添加' }}企业</div>
    <el-form
      style="width:40%;margin:15px 0 0 15px"
      label-position="left"
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
    >
      <el-form-item label="企业全称" prop="companyName">
        <el-input
          placeholder="请输入"
          v-model="ruleForm.companyName"
          :disabled="check"
        ></el-input>
      </el-form-item>
      <el-form-item label="企业行业">
        <el-input
          placeholder="请输入"
          v-model="ruleForm.companyType"
          :disabled="check"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户姓名">
        <el-input
          placeholder="请输入"
          v-model="ruleForm.nickName"
          :disabled="check"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户职业">
        <el-input
          placeholder="请输入"
          v-model="ruleForm.note"
          :disabled="check"
        ></el-input>
      </el-form-item>

      <el-form-item label="企业地址" required>
        <el-col :span="10">
          <el-form-item prop="addressType">
            <el-select
              v-model="ruleForm.addressType"
              placeholder="请选择"
              @change="handleCity"
              :disabled="check"
            >
              <el-option
                v-for="item in optionList1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item prop="cityId">
            <el-select
              v-model="ruleForm.cityId"
              placeholder="请选择"
              :disabled="check"
            >
              <el-option
                v-for="item in optionList2"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item label="详细地址">
        <el-input
          placeholder="请输入"
          v-model="ruleForm.address"
          :disabled="check"
        ></el-input>
      </el-form-item>
      <el-form-item label="登录手机号" prop="username">
        <el-input
          placeholder="请输入"
          v-model="ruleForm.username"
          :disabled="check"
        ></el-input>
      </el-form-item>
      <el-form-item label="登录密码" prop="password" v-if="!editPage">
        <el-input
          placeholder="请输入"
          v-model="ruleForm.password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item label="企业画像" prop="labelIdList">
        <el-button size="small" @click="open" v-if="!check">设置</el-button>
        <div v-else>
          <el-tag style="margin-right:10px" v-for="(item,index) in arr" :key="index">{{item}}</el-tag>
        </div>
      </el-form-item>
      <el-form-item label="头像" prop="icon">
        <multi-upload
          v-model="selectProductPics"
          :maxCount="1"
          :check="check"
        ></multi-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')" v-if="!check"
          >确定</el-button
        >
      </el-form-item>
    </el-form>

    <el-dialog title="企业画像设置" :visible.sync="dialogVisible" width="20%">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item
          :label="item.name"
          v-for="(item, index) in labelList"
          :key="item.id"
        >
          <el-select v-model="arr[index]" placeholder="请选择" clearable>
            <el-option
              v-for="i in item.labelList"
              :key="i.id"
              :label="i.name"
              :value="i.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setIds">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getDictListByStatus } from '@/api/technology/demand';
import {
  checkPhoneExist,
  addCompanyUser,
  updateCompanyUser,
  getCompanyUserInfo,
  getLabelSetting as getOptions
} from '@/api/customer';
import { getCompanyUserInfoByUserId } from '@/api/account';
import { getLabelSetting } from '@/api/policy/library';
import MultiUpload from '@/components/Upload/multiUpload';
export default {
  components: {
    MultiUpload
  },
  data() {
    var validatorPhone = function(rule, value, callback) {
      if (value === '') {
        callback(new Error('手机号不能为空'));
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error('手机号格式错误'));
      } else {
        callback();
        // verifyPhoneNumber(value, function(data) {
        //   callback(data.state ? data.text : new Error(data.text));
        // });
      }
    };
    // var verifyPhoneNumber = function(value, callback) {
    //   checkPhoneExist({ phone: value }).then(({ data }) => {
    //     if (data !== 200) {
    //       callback({
    //         state: false,
    //         text: '该手机号已被注册'
    //       });
    //     }
    //   });
    // };
    return {
      editPage: false,
      check: false,
      ruleForm: {
        companyName: '',
        companyType: '',
        nickName: '',
        note: '',
        addressType: '',
        cityId: '',
        address: '',
        username: '',
        password: '',
        labelIdList: '', // 企业画像
        icon: ''
      },
      optionList1: [
        {
          value: 1,
          label: '地级市'
        },
        {
          value: 2,
          label: '合肥区县'
        }
      ],
      optionList2: [],
      dialogVisible: false,
      form: {},
      labelList: [],
      arr: [],
      rules: {
        companyName: [{ required: true, message: '请输入', trigger: 'blur' }],
        addressType: [{ required: true, message: '请选择', trigger: 'change' }],
        cityId: [{ required: true, message: '请选择', trigger: 'change' }],
        maturityId: [{ required: true, message: '请选择', trigger: 'change' }],
        // username: [{ required: true, message: '请填写', trigger: 'blur' }],
        username: [
          { required: true, validator: validatorPhone, trigger: 'blur' }
        ],
        password: [{ required: true, message: '请填写', trigger: 'blur' }],
        text: [{ required: true, message: '请填写内容', trigger: 'blur' }],
        labelIdList: [
          { required: true, message: '请选择至少一项', trigger: 'blur' }
        ],
        icon: [{ required: true, message: '请上传', trigger: 'blur' }]
      }
    };
  },
  computed: {
    //主图和画册图片
    selectProductPics: {
      get: function() {
        let pics = [];
        if (
          this.ruleForm.icon === undefined ||
          this.ruleForm.icon == null ||
          this.ruleForm.icon === ''
        ) {
          return pics;
        }
        pics.push(this.ruleForm.icon);
        if (
          this.ruleForm.albumPics === undefined ||
          this.ruleForm.albumPics == null ||
          this.ruleForm.albumPics === ''
        ) {
          return pics;
        }
        let albumPics = this.ruleForm.albumPics.split(',');
        for (let i = 0; i < albumPics.length; i++) {
          pics.push(albumPics[i]);
        }
        return pics;
      },
      set: function(newValue) {
        if (newValue == null || newValue.length === 0) {
          this.ruleForm.icon = null;
          this.ruleForm.albumPics = null;
        } else {
          this.ruleForm.icon = newValue[0];
          this.ruleForm.albumPics = '';
          if (newValue.length > 1) {
            for (let i = 1; i < newValue.length; i++) {
              this.ruleForm.albumPics += newValue[i];
              if (i !== newValue.length - 1) {
                this.ruleForm.albumPics += ',';
              }
            }
          }
        }
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.editPage) {
            // 修改
            checkPhoneExist({
              phone: this.ruleForm.username,
              userId: this.ruleForm.userId
            }).then(({ data }) => {
              if (data === 500) return this.msgError('该手机号已被注册');
              updateCompanyUser(this.ruleForm).then(({ message }) => {
                this.msgSuccess(message);
                this.$router.go(-1);
              });
            });
          } else {
            // 添加
            checkPhoneExist({ phone: this.ruleForm.username }).then(
              ({ data }) => {
                if (data === 500) return this.msgError('该手机号已被注册');
                addCompanyUser(this.ruleForm).then(({ message }) => {
                  this.msgSuccess(message);
                  this.$router.go(-1);
                });
              }
            );
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 地级市切换
    handleCity(e) {
      this.ruleForm.cityId = '';
      // 地级市
      if (e === 1) {
        this.getType(false);
      } else {
        this.getCity(false);
      }
    },
    // 获取地级市
    getType(edit, info) {
      getDictListByStatus({ type: 5 }).then(({ data }) => {
        this.optionList2 = data;
        console.log(info);
        if (edit) this.ruleForm = info;
      });
    },
    // 获取地级市
    getCity(edit, info) {
      getDictListByStatus({ type: 6 }).then(({ data }) => {
        this.optionList2 = data;
        console.log(info);
        if (edit) this.ruleForm = info;
      });
    },
    open() {
      this.dialogVisible = true;
    },
    setIds() {
      this.ruleForm.labelIdList = this.arr.filter(item => item);
      this.dialogVisible = false;
    }
  },
  created() {
    let { id } = this.$route.query;
    let { check } = this.$route.query;
    check = Boolean(check);
    if (check) this.check = check;

    if (id) {
      this.editPage = true;
      if(!this.check){
        getOptions({ companyId: id }).then(({ data }) => {
        this.labelList = data;
        this.arr = data.map(item =>
          item.labelList
            ? item.labelList.filter(v => v.isHas)[0]
              ? item.labelList.filter(v => v.isHas)[0].id
              : ''
            : undefined
        );
        getCompanyUserInfo({ companyId: id }).then(({ data }) => {
          data.addressType = data.addressType - 0;
          console.log(this.arr);
          data.labelIdList = this.arr.filter(item => item);
          console.log(data);
          if (data.addressType == 1) {
            this.getType(true, data);
          } else {
            this.getCity(true, data);
          }
        });
      });
      }else{
        
        // 账户管理
              getCompanyUserInfoByUserId({ userId: id }).then(({ data }) => {
                data.addressType = data.addressType - 0;
                getOptions({ companyId: data.companyId }).then(({ data }) => {
        this.labelList = data;
        this.arr = data.map(item =>
          item.labelList
            ? item.labelList.filter(v => v.isHas)[0]
              ? item.labelList.filter(v => v.isHas)[0].name
              : ''
            : undefined
        );
        });
                if (data.addressType == 1) {
                  this.getType(true, data);
                } else {
                  this.getCity(true, data);
                }
              });
      
         
      }
    } else {
      getLabelSetting({
        policyId: 1,
        pageNum: 1,
        pageSize: 100
      }).then(({ data }) => {
        this.labelList = data.list.slice(1);
        this.arr = data.list.map(item =>
          item.labelList
            ? item.labelList.filter(v => v.isHas)[0]
              ? item.labelList.filter(v => v.isHas)[0].id
              : ''
            : undefined
        );
      });
    }
  }
};
</script>
