<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="12vh"
    width="800px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @close="closeModel"
  >
    <el-card style="margin-top: -25px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :rules="rulesThis"
            label-width="110px"
            class="demo-ruleForm"
          >
            <el-form-item :disabled="isDetail" label="账号" prop="username">
              <el-input
                v-model="ruleForm.username"
                placeholder="XXXXXXXXX"
                :disabled="isDetail !== '003'"
                ><template slot="prepend">CJ1745</template></el-input
              >
            </el-form-item>
            <el-form-item
              v-if="isDetail === '003'"
              :disabled="isDetail"
              label="密码"
              prop="password"
            >
              <el-input
                v-model="ruleForm.password"
                placeholder="密码"
                :disabled="isDetail === '007'"
              />
            </el-form-item>
            <el-form-item label="有效期" prop="starttime">
              <!--isDetail === '007'-->
              <PeriodDateTimePicker
                :start="ruleForm.starttime"
                :end="ruleForm.expiretime"
                :type="1"
                :disabled="true"
                :width="'288px'"
                @timeReturned="timeReturned($event)"
              />
            </el-form-item>
            <el-form-item label="客户姓名" prop="nickname">
              <el-input
                v-model="ruleForm.nickname"
                placeholder="客户姓名"
                :disabled="isDetail === '007'"
              />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input
                v-model="ruleForm.mobile"
                placeholder="手机号"
                :disabled="isDetail === '007'"
              />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="ruleForm.remark"
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 4 }"
                placeholder="备注"
                :disabled="isDetail === '007'"
                maxlength="250"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="视频设置" prop="video">
              <div class="video-set">
                <el-select
                  ref="videoSet"
                  style="display: block"
                  v-show="isDetail !== '007'"
                  v-model="value"
                  filterable
                  remote
                  placeholder="请输入视频名称"
                  :remote-method="remoteMethod"
                  @change="selectTags"
                  :loading="loading_video_set"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.video_name"
                    :disabled="item.status === '0'"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
                <el-tag
                  v-show="tags && tags.length > 0"
                  style="margin: 10px 6px"
                  v-for="(tag, index) in tags"
                  :key="tag.name + index"
                  :disable-transitions="true"
                  :closable="isDetail !== '007'"
                  @close="handleClose(tag)"
                  :type="tag.status === '0' ? 'info' : ''"
                >
                  {{ tag.video_name }}
                </el-tag>
              </div>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="24" style="text-align: right">
          <el-button
            v-if="isDetail !== '007'"
            type="primary"
            @click="submitForm"
            >保 存
          </el-button>
          <el-button @click="showModelThis = false">{{
            isDetail !== "007" ? "取 消" : "关 闭"
          }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from "@/apis/service/mobile/park";
import resToken from "@/mixins/resToken";
import PeriodDateTimePicker from "@/components/PeriodDateTimePicker";
import {
  isnumber,
  isMobile,
  isChinese,
  isEmoticon,
  validAlphabets,
} from "@/utils/validate";
export default {
  name: "park",
  props: ["showModel", "id", "isDetail", "sitem"],
  mixins: [resToken],
  components: {
    PeriodDateTimePicker,
  },
  data() {
    const validateusername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("账号不能为空！"));
      } else {
        if (value.length !== 9) {
          callback(new Error("账号不正确！"));
        } else {
          let a = value.slice(0, 3);
          let b = value.slice(3, 9);
          if (a == "TKS" || a == "TKR") {
            if (!isnumber(b)) {
              callback(new Error("账号不正确！"));
            } else {
              callback();
            }
          } else {
            callback(new Error("账号不正确！"));
          }
        }
      }
    };
    const validatepassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("密码不能为空！"));
      } else {
        if (value.length !== 6) {
          callback(new Error("密码规则为2位字母+4位数字组合！"));
        } else {
          let str = value;
          let a = value.slice(0, 2);
          let b = value.slice(2, 4);
          if (!isnumber(b)) {
            callback(new Error("密码规则为2位字母+4位数字组合！"));
          } else if (!validAlphabets(a)) {
            callback(new Error("密码规则为2位字母+4位数字组合！"));
          } else {
            callback();
          }
        }
      }
    };
    const validatetime = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("开始时间不能为空！"));
      } else if (this.ruleForm.expiretime === "") {
        callback(new Error("结束时间不能为空！"));
      } else {
        callback();
      }
    };
    const validatename = (rule, value, callback) => {
      if (value !== "") {
        if (value.length < 2 || value.length > 12) {
          callback(new Error("客户姓名规则为2~12位汉字！"));
        } else {
          if (!isChinese(value)) {
            callback(new Error("客户姓名规则为2~12位汉字！"));
          } else if (isEmoticon(value)) {
            callback(new Error("客户姓名规则为2~12位汉字！"));
          } else {
            callback();
          }
        }
      } else {
        callback();
      }
    };
    const validatemobile = (rule, value, callback) => {
      if (!isMobile(value) && value) {
        callback(new Error("手机号格式不正确！"));
      } else {
        callback();
      }
    };
    return {
      options: [],
      value: [],
      list: [],
      states: [],
      tags: [],
      roleList: [],
      loading: false,
      title: "添加账号",
      showModelThis: this.showModel,
      parmValue: {
        username: "",
        nickname: "",
        status: "",
        mobile: "",
        page: 1,
        size: 15,
        video_id: "",
        id: "",
      },
      ruleForm: {
        username: "",
        password: "",
        starttime: "",
        expiretime: "",
        nickname: "",
        mobile: "",
        remark: "",
        video: [],
        id: "",
      },
      videoForm: {
        page: 1,
        size: 15,
        status: "",
        video_sn: "",
        video_name: "",
        video_url: "",
      },
      videoList: [],
      rulesThis: this.rules,
      rules: {
        username: [
          {
            required: true,
            validator: validateusername,
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            validator: validatepassword,
            trigger: "blur",
          },
        ],
        starttime: [
          {
            required: true,
            validator: validatetime,
            trigger: "blur",
          },
        ],
        nickname: [
          {
            required: false,
            validator: validatename,
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: false,
            validator: validatemobile,
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: false,
            trigger: "blur",
          },
        ],
        video: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个视频",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    restSearch() {
      this.select = "1";
      this.input = "";
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      this.parmValue = {
        username: "",
        nickname: "",
        status: "",
        mobile: "",
        page: 1,
        size: 15,
        id: "",
      };
    },
    selectTags(id) {
      let selectObj = {};
      this.states.filter((item) => {
        if (item.id === id) {
          selectObj.video_name = item.video_name;
          selectObj.id = item.id;
          selectObj.status = item.status;
          this.tags.push(selectObj);
        }
      });
      this.ruleForm.video.push(selectObj.id);
    },
    async handleClose(tag) {
      this.tags.splice(this.tags.indexOf(tag), 1);
      this.ruleForm.video.splice(this.ruleForm.video.indexOf(tag.video_id), 1);
    },
    async remoteMethod(query) {
      this.videoForm.video_name = query;
      this.videoForm.size = 100;
      const res = await asyncRequest.videoList(this.videoForm);
      this.states = res.data.video;
      if (res && res.code === 0 && res.data) {
        if (query !== "") {
          this.loading_video_set = true;
          this.options = res.data.video;
        } else {
          this.options = [];
        }
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      }
      this.loading_video_set = false;
    },
    closeModel() {},
    async initForm() {
      this.loading = true;
      if (this.isDetail === "003") {
        this.title = "添加账号";
        this.rulesThis = this.rules;
        await this.resetForm();
      } else {
        if (this.isDetail === "007") {
          this.title = "账号详情";
          this.rulesThis = {};
        } else {
          this.title = "修改账号";
          this.rulesThis = this.rules;
        }
        await this.resetForm();
        await this.initData();
      }
      this.loading = false;
    },
    async initData() {
      const res = await asyncRequest.detail({ id: this.id });
      if (res && res.code === 0 && res.data) {
        const {
          username,
          info,
          password,
          starttime,
          expiretime,
          nickname,
          mobile,
          remark,
        } = res.data;
        this.tags = info;
        let arr = [];
        this.tags.forEach((v1) => {
          arr.push(v1.video_id);
        });
        this.ruleForm = {
          username: username.substr(username.length - 6),
          password,
          starttime,
          expiretime,
          nickname,
          mobile,
          remark,
          video: arr,
          id: this.id,
        };
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      }
    },
    async resetForm() {
      this.tags = [];
      this.options = [];
      this.value = [];
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.videoSet.$data.selectedLabel = "";
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.ruleForm = {
            username: "",
            password: "",
            starttime: "",
            expiretime: "",
            nickname: "",
            mobile: "",
            remark: "",
            video: [],
          };
        }
      });
    },
    async timeReturned(e) {
      if (e.startTime !== "") {
        this.ruleForm.starttime = e.startTime;
      } else {
        this.ruleForm.starttime = "";
      }
      if (e.endTime !== "") {
        this.ruleForm.expiretime = e.endTime;
      } else {
        this.ruleForm.expiretime = "";
      }
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          let model = Object.assign({}, this.ruleForm);
          model.username = "CJ1745" + model.username;
          let isok = true;
          this.tags.forEach((v1) => {
            if (v1.status === "0") {
              isok = false;
            }
          });
          if (!isok) {
            this.$message.warning("不能绑定已禁用的视频！");
            this.loading = false;
            return;
          }

          let res = {};
          if (this.id === "add") {
            res = await asyncRequest.add(model);
          } else {
            res = await asyncRequest.update(model);
          }
          this.loading = false;
          if (res && res.code === 0) {
            const title = this.id === "add" ? "添加成功" : "修改成功";
            this.$notify.success({
              title,
              message: "",
            });
            this.showModelThis = false;
            this.$emit("refresh");
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.msg);
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

