<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      ref="crud"
      v-model="form"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="addView">新 增</el-button>
      </template>
      <template slot="websiteUrlValidateForm">
        <el-form-item prop="websiteUrlValidate">
          <el-input placeholder="请输入网址" v-model="websiteUrl"></el-input>
        </el-form-item>
      </template>
      <!--自定义操作栏-->
      <div slot="menu" slot-scope="{ size, type, row }">
        <el-button
          icon="el-icon-view"
          :size="size"
          :type="type"
          @click.stop="rowView(row)"
        >查看</el-button>
        <el-button
          icon="el-icon-edit"
          :size="size"
          :type="type"
          @click.stop="rowEdit(row)"
        >编辑</el-button>
        <el-button
          v-if="!row.accountExist"
          icon="el-icon-user"
          :size="size"
          :type="type"
          @click.stop="rowAdd(row)"
        >新建账号</el-button>
        <el-button
          v-if="row.accountExist"
          icon="el-icon-user"
          :size="size"
          :type="type"
          @click.stop="rowCheck(row)"
        >查看账号</el-button>
      </div>
    </avue-crud>

    <!-- 新建账号 / 查看账号 -->
    <el-drawer
      size="50%"
      :visible.sync="stationAddDrawer"
      direction="rtl">
      <template slot="title">
        <span>{{stationAddTitle ? '查看账号' : '添加账号'}}</span>
      </template>
      <div>
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template slot="title">
              <i class="iconfont icon-yonghu"></i>
              <span>基础信息</span>
            </template>
            <el-form :model="stationAddForm" :rules="statusAddRules" ref="stationAddJC" label-width="100px" class="demo-ruleForm">
              <el-col :span="11">
                <el-form-item label="账号:" prop="account" >
                  <el-input v-model="stationAddForm.account" placeholder="请输入 手机号" :disabled="stationAddTitle" :class="{'inputBorderDisabled': stationAddTitle}" @blur="blurInput"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="密码:" prop="password">
                  <el-input v-model="stationAddForm.password" placeholder="请输入 密码" :disabled="stationAddTitle" :class="{'inputBorderDisabled': stationAddTitle}"></el-input>
                </el-form-item>
              </el-col>
            </el-form>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template slot="title">
              <i class="iconfont iconorder"></i>
              <span>详细信息</span>
            </template>
            <el-form :model="stationAddForm" :rules="statusAddRules" ref="stationAddXX" label-width="100px" class="demo-ruleForm">
              <el-col :span="11">
                <el-form-item label="用户姓名:" prop="name" >
                  <el-input v-model="stationAddForm.name" placeholder="请输入 用户姓名" :disabled="stationAddTitle" :class="{'inputBorderDisabled': stationAddTitle}"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="身份证号:" prop="idNumber" >
                  <el-input v-model="stationAddForm.idNumber" placeholder="请输入 身份证号" :disabled="stationAddTitle" :class="{'inputBorderDisabled': stationAddTitle}"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="用户性别:">
                  <el-select v-model="stationAddForm.sex" placeholder="请选择 用户性别" :disabled="stationAddTitle"  :class="{'inputBorderDisabled': stationAddTitle}">
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="用户生日:">
                  <el-date-picker
                    :class="{'inputBorderDisabled': stationAddTitle}"
                    :disabled="stationAddTitle"
                    v-model="stationAddForm.birthday"
                    type="date"
                    value-format="yyyy-MM-dd hh:mm:ss"
                    placeholder="请输入 用户生日">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-form>
          </el-collapse-item>
          <el-collapse-item name="3">
            <template slot="title">
              <i class="iconfont icon-yonghu"></i>
              <span>职责信息</span>
            </template>
            <el-form label-width="100px" class="demo-ruleForm">
              <el-col :span="11">
                <el-form-item label="开通产品:">工作站账号
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="所属角色:">工作站管理员
                </el-form-item>
              </el-col>
            </el-form>
          </el-collapse-item>
        </el-collapse>
        <div style="height: 10px;"></div>
        <div v-if="!stationAddTitle" style="text-align: right;">
          <el-button type="primary" size="small" icon="el-icon-check" :loading="addLoading" @click="handleAddSubmit">提 交</el-button>
          <el-button size="small" icon="el-icon-delete" @click="handleAddClear">清 空</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 新增 or 查看  -->
    <el-drawer
      size="50%"
      :visible.sync="stationLookDrawer"
      direction="rtl">
      <template slot="title">
        <span>{{stationLookTitle | stationLookTitle}}</span>
      </template>
      <el-form :model="stationLookForm" :rules="stationLookRules" ref="stationLook" label-width="100px" class="demo-ruleForm">
        <el-row>
          <el-col :span="11">
            <el-form-item label="工作站:" prop="stationName" >
              <el-input v-model="stationLookForm.stationName" placeholder="请输入工作站"
                        :disabled="stationLookTitle === 2"
                        :class="{'inputBorderDisabled': stationLookTitle === 2}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="结算比例:" prop="percent" >
              <el-input v-model="stationLookForm.percent" type="number" min="0" placeholder="请输入结算比例"
                        :disabled="stationLookTitle === 2"
                        :class="{'inputBorderDisabled': stationLookTitle === 2}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="stationLookTitle === 2" label="所属主体:">
          <el-input v-model="stationLookForm.companyName"
                    :disabled="stationLookTitle === 2"
                    :class="{'inputBorderDisabled': stationLookTitle === 2}"></el-input>
        </el-form-item>
        <el-form-item v-if="stationLookTitle !== 2" label="所属主体:" prop="stationIdn">
          <el-select v-model="stationLookForm.stationIdn" placeholder="请选择"
                     :disabled="stationLookTitle === 2"
                     :class="{'inputBorderDisabled': stationLookTitle === 2}" @change="selectStation">
            <el-option
              v-for="item in stationIdList"
              :key="item.id"
              :label="item.companyName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="网站地址:">
          <el-input v-model="stationLookForm.websiteUrl" :placeholder="stationLookTitle === 2 ? '' : '请输入网站地址'"
                    :disabled="stationLookTitle === 2"
                    :class="{'inputBorderDisabled': stationLookTitle === 2}">
          </el-input>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="stationLookForm.remarks" type="textarea" maxlength="50" :placeholder="stationLookTitle === 2 ? '' : '请输入备注'"
                    :disabled="stationLookTitle === 2"
                    :class="{'inputBorderDisabled': stationLookTitle === 2}"></el-input>
        </el-form-item>
      </el-form>
      <div style="height: 10px;"></div>
      <div style="text-align: right;"  v-if="stationLookTitle === 1 || stationLookTitle === 3">
        <el-button type="primary" size="small" icon="el-icon-check" :loading="lookLoading" @click="stationAddM">保 存</el-button>
        <el-button size="small" icon="el-icon-delete" @click="stationClose">取 消</el-button>
      </div>
    </el-drawer>
  </basic-container>
</template>

<script>
import { getList, update, getDetail, StationFind, StationSave, stationSubmit, tuserDetail, stationModify } from "@/api/manage/station";
import { mapGetters } from "vuex";
import { isvalidatemobile, check18IdCardNo } from "@/util/validate";

var validateStationName = (rule, value, callback)=>{
  const reg = /^\d+(\.\d{0,2})?$/;
  if (Number(value) < 0) {
    callback(new Error('最小输入0'));
  } else
  if (Number(value) > 1) {
    callback(new Error('最大输入1'));
  } else
  if (!reg.test(value)){
    callback(new Error('最多输入小数点后两位'));
  } else {
    callback();
  }
};
var validatorAccount = (rule, value, callback)=>{
  if (isvalidatemobile(value)[0]) {
    callback(new Error(isvalidatemobile(value)[1]));
  } else {
    callback();
  }
}
var validatorIdNumber = (rule, value, callback)=>{
  if (check18IdCardNo(value)) {
    callback();
  } else {
    callback(new Error("身份证格式不正确"));
  }
}

// var dic = [{
//   value: 'test工作站value',
//   label: 'test工作站table'
// }];
export default {
  name: "manage_station_stationList",
  data() {
    return {
      stationIdList: [],
      activeNames: ['1', '2', '3'],
      statusAddRules: {
        account: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatorAccount, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' }
        ],
        idNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: validatorIdNumber, trigger: 'blur' }
        ],
      },
      stationAddForm: {},
      stationLookRules: {
        stationName: [
          { required: true, message: '请输入工作站', trigger: 'blur' }
        ],
        percent: [
          { required: true, message: '请输入结算比例', trigger: 'blur' },
          { validator: validateStationName, trigger: 'blur' }
        ],
        stationIdn: [
          { required: true, message: '请选择主体', trigger: 'blur' }
        ]
      },
      stationLookForm: {},
      form: {},
      selectionList: [],
      query: {},
      addLoading: false,
      lookLoading: false,
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      stationLookDrawer: false,
      stationLookTitle: 1,
      stationAddTitle: false,
      stationAddDrawer: false,
      drawerVisible: false,
      option: {
        height: "auto",
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: "序号",
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtn:false,
        menuWidth: 280,
        dialogType: "drawer",
        column: [
          {
            label: "id",
            prop: "id",
            hide: true,
            display: false,
          },
          {
            label: "站点编号",
            prop: "stationId",
          },
          {
            label: "工作站",
            prop: "stationName",
            search: true,
            rules: [
              {
                required: true,
                whitespace: true,
                message: "请输入工作站",
                trigger: "blur",
              },
            ],
          },
          {
            label: "结算比例",
            prop: "percent",
            display: false,
            editDisplay: false,
          },
          {
            label: "主体信息",
            prop: "companyName",
            display: false,
            editDisplay: false,
          },
          {
            label: "网站地址",
            prop: "websiteUrl",
            span: 12,
            search: false,
            formslot: false,
            display: false,
          },
          {
            label: "网站地址",
            prop: "websiteUrlValidate",
            span: 12,
            search: false,
            formslot: true,
            hide: true,
            rules: [
              {
                type: "url",
                message: "请输入正确的网站地址",
              },
            ],
          },
          {
            type: "textarea",
            label: "备注",
            span: 24,
            prop: "introduce",
            hide: true,
            rules: [
              {
                required: false,
                message: "请输入备注",
                trigger: "blur",
              },
            ],
            showWordLimit: true,
            maxlength: 50,
          },
        ]
      },
      data: [],
      rowDetail: {}
    };
  },
  filters: {
    stationLookTitle (v) {
      switch (v) {
        case 1:
          return '新 增';
        case 2:
          return '查 看';
        case 3:
          return '编 辑';
      }
    }
  },
  created() {
    StationFind().then(res => {
      this.stationIdList = res.data.data
    })
    // StationDic().then(res => {
    //   this.stationIdList = res.data.data
    // })
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    // permissionList() {
    //   return {
    //     addBtn: this.vaildData(
    //       this.permission.manage_station_stationList_add,
    //       false
    //     ),
    //     viewBtn: this.vaildData(
    //       this.permission.manage_station_stationList_view,
    //       false
    //     ),
    //     editBtn: this.vaildData(
    //       this.permission.manage_station_stationList_edit,
    //       false
    //     ),
    //   };
    // },
    websiteUrl: {
      get() {
        if (this.form.websiteUrl) {
          return this.form.websiteUrl;
        } else {
          return "";
        }
      },
      set(val) {
        if (val) {
          this.$set(this.form, "websiteUrlValidate", `http://${val}`);
        } else {
          this.$set(this.form, "websiteUrlValidate", "");
        }
        this.$set(this.form, "websiteUrl", val);
      },
    },
  },
  methods: {
    blurInput () {
      var str = JSON.parse(JSON.stringify(this.stationAddForm.account))
      var password = str.substr(str.length - 6, str.length)
      this.stationAddForm.password = password
      this.$forceUpdate()
    },
    // 新增站点 提交
    stationAdd(){
      this.lookLoading = true
      let tenantId;
      this.stationIdList.forEach((item) => {item.id == this.stationLookForm.stationIdn ? tenantId= item.tenantId:''});
      let obj = {
        stationName: this.stationLookForm.stationName,
        percent: this.stationLookForm.percent,
        companyId: this.stationLookForm.stationIdn,
        websiteUrl: this.stationLookForm.websiteUrl,
        remarks: this.stationLookForm.remarks,
        tenantId: tenantId,
      }
      StationSave(obj).then(() => {
        this.lookLoading = false
        this.onLoad(this.page, this.query);
        this.$message({
          type: "success",
          message: "操作成功!",
        });
        this.stationLookDrawer = false
      }).catch(() => {
        this.lookLoading = false
      })
    },
    selectStation () {
      this.$forceUpdate()
    },
    stationUpdate(){
      this.lookLoading = true
      let tenantId;
      this.stationIdList.forEach((item) => {item.id == this.stationLookForm.stationIdn ? tenantId= item.tenantId:''});
      var obj = {
        stationName: this.stationLookForm.stationName,
        percent: this.stationLookForm.percent,
        companyId: this.stationLookForm.stationIdn,
        websiteUrl: this.stationLookForm.websiteUrl,
        remarks: this.stationLookForm.remarks,
        tenantId: tenantId,
        id: this.stationLookForm.id,
        stationId: this.stationLookForm.stationId
      }
      stationModify(obj)
        .then(() => {
          this.lookLoading = false
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.stationLookDrawer = false
        }).catch(() => {
            this.lookLoading = false
        })
    },
    //  新增 / 修改 站点
    stationAddM () {
      // stationLookTitle = 1 新增
      // stationLookTitle = 3 修改
      this.$refs['stationLook'].validate((valid) => {
        if (valid) {
          if (this.stationLookTitle === 1) {
            this.stationAdd()
          } else if (this.stationLookTitle === 3) {
            this.stationUpdate()
          }
        } else {
          return false;
        }
      });
    },
    stationClose () {
      // 取消新增站点
      this.stationLookDrawer = false
    },
    // 新建账号 提交
    handleAddSubmit () {
      this.$refs['stationAddJC'].validate((valid) => {
        if (valid) {
          this.$refs['stationAddXX'].validate((valid) => {
            if (valid) {
              let obj = {
                authType: 2,
                account: this.stationAddForm.account,
                password: this.stationAddForm.password,
                name: this.stationAddForm.name,
                idNumber: this.stationAddForm.idNumber,
                sex: this.stationAddForm.sex,
                birthday: this.stationAddForm.birthday,
                tenantId: this.rowDetail.tenantId,
                companyId: this.rowDetail.companyId,
                stationId: this.rowDetail.stationId
              }
              this.addLoading = true
              stationSubmit(obj).then(() => {
                this.addLoading = false
                this.onLoad(this.page, this.query);
                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
                this.stationAddDrawer = false
              }).catch(() =>{
                this.addLoading = false
              })
            } else {
              return false;
            }
          });
        } else {
          return false;
        }
      });
    },
    //查看账号
    rowCheck(row){
      this.handleAddClear()
      var params = {
        companyId: row.companyId,
        authType: 2
      }
      tuserDetail(params).then(res => {
        this.stationAddTitle = true
        this.stationAddDrawer = true
        this.stationAddForm.account = res.data.data.account
        this.stationAddForm.password = '******'
        this.stationAddForm.name = res.data.data.name
        this.stationAddForm.idNumber = res.data.data.idNumber
        this.stationAddForm.sex = res.data.data.sexName
        this.stationAddForm.birthday = res.data.data.birthday
        this.$nextTick(() => {
          this.clearVail()
        })
      })
    },
    handleAddClear () {
      this.stationAddForm = {}
    },
    // 新增
    addView(){
      this.stationLookForm = {}
      this.stationLookTitle = 1
      StationFind().then(res => {
        this.stationIdList = res.data.data
        this.stationLookDrawer = true
        this.$nextTick(() => {
          this.clearVailLook()
        })
      })
    },
    //查看
    rowView(row){
      this.stationLookForm = row
      this.stationLookTitle = 2
      this.stationLookDrawer = true
      this.$nextTick(() => {
        this.clearVailLook()
      })
    },
    //编辑
    rowEdit(row){
      this.stationLookForm = JSON.parse(JSON.stringify(row))
      this.stationLookForm.stationIdn = row.companyId
      this.stationLookTitle = 3
      this.stationLookDrawer = true
      this.$nextTick(() => {
        this.clearVailLook()
      })
    },
    //新建账号
    rowAdd(row){
      this.rowDetail = row
      this.handleAddClear()
      this.addLoading = false
      this.stationAddTitle = false
      this.stationAddDrawer = true
      this.$nextTick(() => {
        this.clearVail()
      })
    },
    //清除验证
    clearVail(){
      this.$refs['stationAddJC'].clearValidate();
      this.$refs['stationAddXX'].clearValidate();
    },
    clearVailLook(){
      this.$refs['stationLook'].clearValidate();
    },
    initData() {
      this.onLoad(this.page, this.query);
    },
    rowSave(row, done, loading) {
      console.log('保存 ===', row, done, loading)
      // add(row)
      //   .then(() => {
      //     this.$message({
      //       type: "success",
      //       message: "操作成功!",
      //     });
      //     // 数据回调进行刷新
      //     done(row);
      //     this.refreshChange();
      //   })
      //   .catch((error) => {
      //     window.console.log(error);
      //     loading();
      //   });
    },
    rowUpdate(row, index, done, loading) {
      update(row)
        .then(() => {
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          // 数据回调进行刷新
          done(row);
        })
        .catch((error) => {
          window.console.log(error);
          loading();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    beforeOpen(done, type) {
      if (["add", "edit"].includes(type)) {
        this.initData();
      }
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    beforeClose(done) {
      this.$refs.crud.value.addDisabled = false;
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(this.query, params)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      }).catch(() => {
        this.loading = false
      });
    },
  },
};
</script>

<style>
  .inputBorderDisabled .el-input__inner{
    border: none !important;
    background-color: #FFFFFF !important;
  }
  .inputBorderDisabled .el-textarea__inner{
    border: none !important;
    background-color: #FFFFFF !important;
  }
</style>
