<template>
  <div>
    <Form :model="form" ref="formUser" :rules="rules" :label-width="120" style="margin-bottom: 20px;">
      <FormBlock :title="$t('module.userManage.info')" style="margin-bottom: 20px;">
        <Row :gutter="20" class="code-row-bg">
          <Col span="10">
          <Form-item prop="userCode" :label="$t('module.userManage.account')">
            <Input v-model="form.userCode" :disabled="id != ''" placeholder="" maxlength="30"></Input>
          </Form-item>
          </Col>
          <Col span="10">
          <Form-item prop="userName" :label="$t('module.userManage.name')">
            <Input v-model="form.userName" placeholder="" :disabled="form.type == 1" maxlength="30"></Input>
          </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="10">
          <Form-item prop="mobile" :label="$t('module.userManage.tel')">
            <Input v-model="form.mobile" placeholder="" maxlength="20" :disabled="form.type == 1" style="width:100%"></Input>
            <!-- <DatePicker :value="effectDate"  type="daterange" placement="bottom-end" placeholder="" @on-change="handleDateChange" style="width:100%"></DatePicker> -->
          </Form-item>
          </Col>
          <Col span="10">
          <Form-item prop="effectDate" :label="$t('common.validDate')">
            <DatePicker :value="effectDate" transfer="true" type="daterange" placement="bottom-end" placeholder="" @on-change="handleDateChange" style="width:100%"></DatePicker>
          </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="10">
          <Form-item prop="email" :label="$t('common.email')">
            <Input v-model="form.email" placeholder="" maxlength="100" :disabled="form.type == 1"></Input>
          </Form-item>
          </Col>
          <Col span="10">
          <Form-item prop="enabled" :label="$t('module.userManage.status')">
            <Select v-model="form.enabled">
              <Option :value="1">{{$t("common.enable")}}</Option>
              <Option :value="0">{{$t("common.disable")}}</Option>
            </Select>
          </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="10">
          <Form-item prop="orgName" :label="$t('common.organization')">
            <Tag type="dot" color="blue" v-if="form.orgId">
              {{form.orgName}}
            </Tag>
            <Button type="primary" @click="showOrg" icon="md-create" size="small" :disabled="form.type == 1"></Button>
          </Form-item>
          </Col>
          <Col span="10">
          </Col>
        </Row>
        <!-- <Row :gutter="20" class="code-row-bg">
            <Col span="10">
            <Form-item prop="pwdLocked" label="密码5次错误锁定">
              <Input v-model="pwdLocked" placeholder="" maxlength="20" readonly></Input>
            </Form-item>
            </Col>
          </Row> -->
        <!-- <Row :gutter="20" class="code-row-bg" v-if="!id">
            <Col span="10">
            <Form-item prop="passWord" :label="$t('module.userManage.initPassword')">
              <Input v-model="form.passWord" type="password" placeholder="" maxlength="18"></Input>
            </Form-item>
            </Col>
            <Col span="10">
            </Col>
          </Row> -->
      </FormBlock>
      <FormBlock :title="$t('module.userManage.role')">
        <Button class="ivu-btn-hr" slot="tool-bar" size="small" icon="plus-round" @click="showPushRole">{{$t('common.create')}}</Button>
        <PageTable ref="userRoleTable" :resource="roles" :columns="columns" :isPage="false"></PageTable>
        <!-- <Tag type="dot" closable color="blue" @on-close="handleClose(index)" v-for="(item,index) in roles" :key="index">{{item.roleName}}</Tag> -->
      </FormBlock>
    </Form>
    <FormBlock :title="$t('module.userManage.extendField')" style="margin-bottom: 20px;">
      <flex-fields ref="fields" code="userFlexField" :fields="form" :orgId="form.orgId" :value="form.sysRegisteruserExt || {}"></flex-fields>
    </FormBlock>
    <FormBlock v-if="initParams.recordId" :title="$t('module.userManage.historyRecord')">
      <PageTable ref="logTable" action="QueryUserLogList" :initParam="initParams" :columnsFn="columnsLog"></PageTable>
    </FormBlock>
  </div>
</template>
<style lang="less" scoped>

</style>
<script>
import ChooseOrg from "../ChooseOrgSingle.vue";
import OperateLogDetail from '../logQuery/OperateLogDetail.vue';
import UserEditRole from "./UserEditRole.vue"
export default {
  components: {},
  props: {
    id: {
      type: String,
      default() {
        return "";
      }
    },
    version: {
      type: Number,
      default() {
        return -1;
      }
    },
  },
  data() {
    const validateOrgName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择组织"));
      }
      callback();
    };
    return {
      // orgIds: [],
      effectDate: ['', ''],
      eventList: [],
      initParams: {
        recordType: "USER",
        recordId: this.id
      },
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: this.$t("module.userManage.roleName"),
          key: "roleName",
          sortable: true,
        },
        {
          title: this.$t("module.userManage.roleCode"),
          sortable: true,
          key: "roleCode",
        },
        {
          title: this.$t("module.userManage.affiliation"),
          sortable: true,
          key: "orgName",
        },
        {
          title: this.$t("common.status"),
          align: "center",
          key: "enabled",
          sortable: true,
          width: 140,
          render: (h, params) => {
            return h(
              "Tag",
              {
                props: {
                  type: "dot",
                  color: !!params.row.enabled ? "blue" : "red"
                }
              },
              !!params.row.enabled ? this.$t("module.userManage.enabled") : this.$t("module.userManage.frozen")
            );
          }
        }
      ],
      form: {
        userCode: "",
        userName: "",
        orgUnitId: "",
        mobile: "",
        passWord: "",
        // roleIds: "",
        locked: "",
        enabled: 1,
        effectBegin: '',
        effectEnd: '',
        type: 2,
        sysUserRoleList: [],
        sysRegisteruserExt: {},
        orgId: "",
        orgName: ""
      },
      roles: [],
      modal: false,
      rules: {
        userCode: [{ required: true, message: this.$t("module.userManage.warning.enterUserAccount"), trigger: "blur" }],
        userName: [{ required: true, message: this.$t("module.userManage.warning.enterUserName"), trigger: "blur" }],
        passWord: [{ required: true, message: this.$t("module.userManage.warning.enterPassword"), trigger: "blur" }],
        // mobile: [
        //   {
        //     required: false, message: this.$t("module.userManage.warning.enterCorrectTel"), trigger: 'blur', pattern: /^1(3|4|5|7|8)\d{9}$/
        //   }
        // ],
        orgName: [{ required: true, validator: validateOrgName, trigger: "blur" }]
      },
      tableData: [],
      columns: [
        {
          title: this.$t("module.userManage.roleName"),
          key: "roleName",
          sortable: true,
        },
        {
          title: this.$t("module.userManage.roleCode"),
          sortable: true,
          key: "roleCode",
        },
        {
          title: this.$t("module.userManage.affiliation"),
          sortable: true,
          key: "orgName",
        },
        {
          title: this.$t("common.status"),
          align: "center",
          key: "enabled",
          sortable: true,
          width: 140,
          render: (h, params) => {
            return h(
              "Tag",
              {
                props: {
                  type: "dot",
                  color: !!params.row.enabled ? "blue" : "red"
                }
              },
              !!params.row.enabled ? this.$t("module.userManage.enabled") : this.$t("module.userManage.frozen")
            );
          }
        },
        {
          title: this.$t('module.userManage.validDateBegin'),
          key: "effectBegin",
          width: 140,
          render: (h, params) => {
            return h('DatePicker',
              {
                props: {
                  size: 'samll',
                  value: params.row.effectBegin,
                  placement: "bottom-top",
                  transfer: true,
                },
                on: {
                  'on-change': (value) => {
                    let i = this.roles.findIndex((role) => {
                      return role.roleId == params.row.roleId;
                    })
                    this.roles[i].effectBegin = value;
                  }
                }
              }
            )
          }
        },
        {
          title: this.$t('module.userManage.validDateEnd'),
          key: "effectEnd",
          width: 140,
          render: (h, params) => {
            return h('DatePicker',
              {
                props: {
                  size: 'samll',
                  value: params.row.effectEnd,
                  placement: "bottom-top",
                  transfer: true,
                },
                on: {
                  'on-change': (value) => {
                    let i = this.roles.findIndex((role) => {
                      return role.roleId == params.row.roleId;
                    })
                    this.roles[i].effectEnd = value;
                  }
                }
              }
            )
          }
        },
        {
          title: this.$t("module.userManage.enabled"),
          key: 'enabled',
          width: 80,
          align: "center",
          render: (h, params) => {
            return h('Checkbox', {
              props: {
                value: params.row.enabled
              },
              on: {
                'on-change': (value) => {
                  let i = this.roles.findIndex((role) => {
                    return role.roleId == params.row.roleId;
                  })
                  this.roles[i].enabled = value;
                  this.$forceUpdate();
                }
              }
            }
            )
          }
        }
      ],
      rolesList: [],
      selection: []
    };
  },
  computed: {
    pwdLocked: function () {
      return this.form.locked == 1 ? this.$t("common.yes") : this.$t("common.no");
    }
  },
  created: function () {
    // setInterval(()=>{
    //  this.$nextTick(()=>{
    //     this.referenceField = String(Math.floor(Math.random() * 100))
    //  })
    // })
    if (this.id) {
      this.$emit("SetPageActions", [
        {
          text: this.$t('module.userManage.passwordToUnlock'),
          theme: "info",
          icon: "unlocked",
          handle: this.unlockedUser
        },
        {
          text: this.$t("common.save"),
          theme: "warning",
          icon: "md-create",
          action: "EditUser",
          handle: this.edit
        }
      ]);
    } else {
      this.$emit("SetPageActions", [
        {
          text: this.$t("common.save"),
          theme: "warning",
          icon: "md-create",
          action: "EditUser",
          handle: this.edit
        }
      ]);
    }
    this.$emit("SetTitle", this.id != "" ? this.$t('module.userManage.editUser') : this.$t('module.userManage.addUser'));
    this.id && this.QueryUserDetail();
    $store.dispatch("GetValueSetByCode", { code: 'EVENT' }).then(response => {
      this.eventList = response.dataResult
    })
  },
  beforeMount: function () { },
  mounted: function () { },
  beforeDestroy: function () { },
  destroyed: function () { },
  methods: {
    edit() {
      this.form.userCode = this.form.userCode.replace(/(^\s*)|(\s*$)/g, "");
      this.form.userName = this.form.userName.replace(/(^\s*)|(\s*$)/g, "");
      this.$refs["formUser"].validate(valid => {
        if (!valid) return;
        // let ids = [];
        this.form.sysUserRoleList = [];
        this.roles.map((role) => {
          this.form.sysUserRoleList.push({
            roleId: role.roleId,
            enabled: role.enabled ? 1 : 0,
            effectBegin: role.effectBegin,
            effectEnd: role.effectEnd
          });
        })
        // for (let o of this.roles) {
        //   // ids.push(o.roleId);
        //   this.form.sysUserRoleList.push({
        //     roleId: o.roleId,
        //     enabled: 1,
        //     effectBegin: o.effectBegin,
        //     effectEnd: o.effectEnd
        //   });
        // }
        // this.form.roleIds = ids.join(",");
        // let ids = [];
        // this.orgIds.map((o) => {
        //   ids.push(o.orgId);
        // })
        // this.form.orgIds = ids.join(",");
        this.$emit("SetActionsState", {
          btn: "EditUser",
          state: true
        });
        // $store.dispatch("EditUser", Object.assign({}, {
        $store.dispatch("EditUser", {
          "userId": this.form.userId,
          "userCode": this.form.userCode,
          "userName": this.form.userName,
          "type": this.form.type,
          "mobile": this.form.mobile,
          "email": this.form.email,
          "enabled": this.form.enabled,
          "effectBegin": this.form.effectBegin,
          "effectEnd": this.form.effectEnd,
          "orgIds": this.form.orgId,
          "sysUserRoleList": this.form.sysUserRoleList,
          "version": this.version
        // }, { sysRegisteruserExt: this.$refs['fields'].getFields() })).then(res => {
        }).then(res => {
          this.$emit("SetActionsState", {
            btn: "EditUser",
            state: false
          });
          if (res.success == true) {
            this.$Message.success({
              content: this.$t("module.userManage.doSuccess"),
              duration: 3
            });
            // return;
          this.$emit("close");
          }else{
            this.$Message.error({
              content: res.msg,
              duration: 3
            });
          }
          return ;
        });
      });
    },
    unlockedUser() {
      $store
        .dispatch("unlockedUserPwd", {
          userId: this.form.userId
        })
        .then(res => {
          if (!res.success) {
            this.$Message.warning({
              content: res.msg,
              duration: 3
            });
            return;
          }
          this.$Message.warning({
            content: this.$t('module.userManage.warning.unlockSuccess'),
            duration: 3
          });
          this.form.locked = 0;
        });
    },
    showOrg() {
      // let sidelipPage = new this.$sidelipPage(
      let pageModal = new this.$pageModal(
        ChooseOrg,
        {
          props: {
            // originalOrgIds: this.orgIds
          },
          on: {
            handler: (org) => {
              this.form.orgId = org.orgId;
              this.form.orgName = org.orgName;
              this.$forceUpdate();
              this.$Message.success({
                content:  this.$t('module.userManage.addOrgSuccess'),
                duration: 3
              })
            }
          }
        },
        () => {}
      );
    },
    QueryUserDetail() {
      $store.dispatch("QueryUserDetail", { userId: this.id }).then(data => {
        Object.assign(this.form, data);
        // console.log((this.form.effectBegin && new Date(this.form.effectBegin).Format("yyyy-MM-dd")), (this.form.effectEnd && new Date(this.form.effectEnd).Format("yyyy-MM-dd")));
        let effectBegin = this.form.effectBegin && new Date(this.form.effectBegin).Format("yyyy-MM-dd");
        let effectEnd = this.form.effectEnd && new Date(this.form.effectEnd).Format("yyyy-MM-dd")
        //给对象重新赋值，而不是改变对象的某个属性。
        this.effectDate = [effectBegin,effectEnd];
        // this.effectDate[0] = effectBegin;
        // this.effectDate[1] = effectEnd;
        this.$forceUpdate();
        data.sysUserRoleList.map((role) => {
          role.enabled = !!Number(role.enabled);
        })
        this.roles = [].concat(data.sysUserRoleList);
        // this.orgIds = [].concat(data.sysUserOrgList);
        if(data.sysUserOrgList.length > 0){
          let org = data.sysUserOrgList[0];
          this.form.orgId = org.orgId;
          this.form.orgName = org.orgName;
        }
        this.$refs['userRoleTable'].refresh();
      });
    },
    handleClose(index) {
      this.roles.splice(index, 1);
    },
    handleDateChange(date) {
      this.form.effectBegin = date[0];
      this.form.effectEnd = date[1];
    },
    showPushRole() {
      new this.$pageModal(
        UserEditRole,
        {
          props: {
            roles: this.roles
          }
        }, (data) => {
          if (!!data) {
            this.roles = this.roles.concat(data);
            this.$refs['userRoleTable'].refresh();
          }
        });
    },
    columnsLog(){
      return [
        {
            title: this.$t('common.operating'),
            align: "center",
            width: 80,
            render: (h, params) => {
              return h("RowTools", {
                props: {
                  data: [
                    {
                      type: "button",
                      text: this.$t('module.logQuery.detail'),
                      handle: () => {
                        new this.$sidelipPage(OperateLogDetail, {
                          props: {
                            logId: params.row.id
                          }
                        }); 
                      }
                    }
                  ]
                }
              });
            }
          },
          {
            title: this.$t('module.logQuery.event'),
            key: "event",
            align: "center",
            width: 150,
            render: (h, params) => {
              return h(
                "span",
                {
                  attrs: {
                    title: this.getEventName(params.row.event)
                  }
                },
                this.getEventName(params.row.event)
              );
            }
          },
          {
            title: this.$t("module.logQuery.createdTime"),
            key: "timestamp",
            align: "center",
            width: 130,
            ellipsis: true,
            render: (h, params) => {
              return h(
                "span",
                {
                  attrs: {
                    title: params.row.timestamp
                  }
                },
                params.row.timestamp
              );
            }
          },
          {
            title: this.$t('module.logQuery.userId'),
            key: "userId",
            width: 120,
            align: "center",
            render: (h, params) => {
              return h(
                "span",
                {
                  attrs: {
                    title: params.row.userId
                  }
                },
                params.row.userId
              );
            }
          },
          {
            title: this.$t('module.logQuery.userName'),
            key: "userName",
            align: "center",
            width: 120,
            render: (h, params) => {
              return h(
                "span",
                {
                  attrs: {
                    title: params.row.userName
                  }
                },
                params.row.userName
              );
            }
          },
          {
            title: this.$t('module.logQuery.userIp'),
            key: "userIP",
            align: "center",
            width: 180,
            render: (h, params) => {
              return h(
                "span",
                {
                  attrs: {
                    title: params.row.userIP
                  }
                },
                params.row.userIP
              );
            }
          },
          {
            title: this.$t('module.logQuery.extra'),
            key: "extra",
            align: "center",
            width: 180,
            ellipsis: true,
            render: (h, params) => {
              return h(
                "span",
                {
                  attrs: {
                    title: params.row.extra
                  }
                },
                params.row.extra
              );
            }
          },
      ]
    },
    getEventName(event){
      for(let item of this.eventList){
        if(event == item.vsiKey){
          return item.vsiValue
        }
      }
    },
  },
  watch: {},
  directives: {}
};
</script>
