<template>
  <el-row>
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="dataSource"
        :page.sync="page"
        ref="crud"
        v-model="crudValues"
        :permission="permissionList"
        @search-change="searchChange"
        @search-reset="searchReset"
        @current-change="currentChange"
        @size-change="sizeChange"
        class="customPage"
      >

        <template slot-scope="{row}" slot="menu">
          <div>
            <el-button type="text"
                       icon="el-icon-document"
                       size="small"
                       @click="serveLog(row)"
            >查看日志
            </el-button>
          </div>
        </template>
      </avue-crud>
    </basic-container>
    <el-drawer
      title="服务日志"
      size="80%"
      :append-to-body="true"
      :before-close="handleCloseLog"
      :visible.sync="innerDrawerLog">
      <!-- <div>
        <span>姓名：</span>
        <span>身份证号：</span>
      </div> -->
      <avue-crud
        :data="logDataSource"
        :option="logOption"
        :page.sync="logPage"
        :table-loading="loadingLog"
        @row-save="saveLog"
        @row-update="saveUpdateLog"
        @row-del="removeLog"
        @size-change="logSizeChange"
        @current-change="logCurrentChange"
      >
        <!-- <template slot="menuLeft">
          <el-button @click="addNewLog" icon="el-icon-plus" type="primary" size="mini">添加</el-button>
        </template>
        <template slot="menu" slot-scope="{row}">
          <el-button type="text" @click="editLogInfo(row.id)" icon="el-icon-edit" size="mini">修改</el-button>
          <el-button type="text" @click="editLogInfo(row.id)" icon="el-icon-edit" size="mini">查看附件</el-button>
        </template> -->
      </avue-crud>
    </el-drawer>
    <el-drawer
      title="新增"
      size="60%"
      :append-to-body="true"
      :before-close="() => innerDrawerAddLog = false"
      :visible.sync="innerDrawerAddLog">
      <avue-form ref="form" :option="logOption" v-model="logValues" @submit="handleSubmitLog"/>
    </el-drawer>
  </el-row>
</template>

<script>
import {mapGetters} from "vuex";
import {getList} from "@/api/tenant/personnelserve";
import {isvalidatemobile} from "@/util/validate";
import {getDept, getDeptMyTree} from "@/api/tenant/talents";
import {addServeLog, getMainServeUserLog, removeServeLog, updateServeLog} from "@/api/tenant/serve";

const page = {
  pageSize: 10,
  currentPage: 1,
  total: 0,
}
const baseOptions = {
  size: 'medium',
  dateBtn: false,
  addBtn: false,
  editBtn: false,
  delBtn: false,
  height: "auto",
  menuWidth: 130,
  reserveSelection: false,
  border: true,
  columnBtn: false,
  refreshBtn: false,
  menu: true,
  tip: false,
  selection: false,
  align: 'center',
  searchMenuSpan: 6,
  searchLabelWidth: 60,
}
export default {
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 15) {
        return value.slice(0, 14) + "...";
      }
      return value;
    },
  },
  data() {
    return {
      loading: false,
      dataSource: [],
      crudValues: {},
      depTree: [],
      page: Object.assign({}, page),
      treeData: [],
      logPage: Object.assign({}, page),
      logDataSource: [],
      loadingLog: false,
      innerDrawerLog: false,
      innerDrawerAddLog: false,
      logValues: {}
    }
  },
  computed: {
    ...mapGetters(["permission", "userInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.tenant_main_talents_latent_index_add, false),
        viewBtn: true,
        delBtn: this.vaildData(this.permission.tenant_main_talents_latent_index_del, false),
        editBtn: this.vaildData(this.permission.tenant_main_talents_latent_index_edit, false),
      };
    },
    option() {
      const self = this;
      const IdCardNo = (rule, value, callback) => {
        // if (check18IdCardNo(value)) {
        callback();
        // } else {
        //   callback(new Error("身份证格式不正确"));
        // }
      };
      const validateTel = (rule, value, callback) => {
        if (isvalidatemobile(value)[0]) {
          callback(new Error(isvalidatemobile(value)[1]));
        } else {
          callback();
        }
      };
      return {
        ...baseOptions,
        column: [
          {
            label: "所属机构",
            prop: "createDept",
            type: "tree",
            multiple: false,
            dicData: this.depTree,
            props: {
              label: "title",
              value: 'value'
            },
            checkStrictly: true,
            span: 24,
            search: true,
            searchLabelWidth: 80,
            change: this.deptChange
          },
          {
            label: "姓名",
            prop: "name",
            // search: true,
            span: 24,
            rules: [
              {
                required: true,
                whitespace: true,
                message: "请输入姓名",
                trigger: "blur",
              },
            ],
            search: true,
          },
          {
            label: "姓别",
            prop: "aac004",
            type: 'select',
            dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC004",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请输入性别",
                trigger: "blur",
              },
            ],
            span: 24,
          },
          {
            label: "身份证",
            prop: "idNumber",
            // hide: true,
            span: 24,
            rules: [
              {required: true, message: "请输入身份证号", trigger: "blur"},
              {trigger: "blur", validator: IdCardNo},
            ],
            search: true,
          },
          {
            label: "手机号",
            prop: "telphone",
            span: 24,
            hide: false,
            rules: [
              {
                required: true,
                validator: validateTel,
                trigger: "blur",
              },
            ],
          },
          {
            label: "民族",
            prop: "aac005",
            type: 'select',
            dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC005",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请输入民族",
                trigger: "blur",
              },
            ],
            span: 24,
          },
          {
            label: "户口性质",
            prop: "aac009",
            type: 'select',
            dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC009",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请输入户口性质",
                trigger: "blur",
              },
            ],
            span: 24,
          },
          {
            label: "户口所在地",
            prop: "aac010",
            // hide: true,
            span: 24,
            rules: [
              {required: true, message: "请输入口所在地", trigger: "blur"},
            ],
          },
          {
            label: "文化程度",
            prop: "aac011",
            type: 'select',
            dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC011",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请输入文化程度",
                trigger: "blur",
              },
            ],
            span: 24,
          },
          {
            label: "备注",
            prop: "remarks",
            type: "textarea",
            slot: true,
            hide: true,
            span: 24,
            maxlength: 100,
            showWordLimit: true,
          },
        ],
      }
    },
    logOption() {
      return {
        editBtn: true,
        delBtn: true,
        addBtn: true,
        viewBtn: true,
        border: true,
        index: true,
        indexLabel: "序号",
        refreshBtn: false,
        dialogType: "drawer",
        addBtnText: "新增日志",
        height: '100',
        column: [{
          label: '服务时间',
          prop: 'createTime',
          type: 'date',
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
          rules: [
            {
              required: true,
              message: "请选择服务时间",
              trigger: "blur",
            },
          ],
        }, {
          label: '服务发起人',
          prop: 'fromName',
          display: false,
        }, {
          label: '服务对象',
          prop: 'toName',
          display: false,
        }, {
          label: '服务主题',
          prop: 'serveTheme',
          rules: [
            {
              required: true,
              message: "请输入服务主题",
              trigger: "blur",
            },
          ],
        }, {
          label: '服务内容',
          type: 'textarea',
          prop: 'serveContent',
          span: 24,
          rules: [
            {
              required: true,
              message: "请输入服务内容",
              trigger: "blur",
            },
          ],
        }, {
          label: '备注说明',
          type: 'textarea',
          prop: 'bak1',
          span: 24,
        }]
      }
    }
  },
  created() {
    this.getDept()
    this.initDept()
    this.onLoad(this.page, this.query)
  },
  methods: {
    async getDept() {
      let params = {
        tenantId: '000000'
      }
      let resData = await getDeptMyTree(params)
      if (resData.data.code === 200) {
        this.depTree = resData.data.data
      }
    },
    initDept(groupId) {
      getDept({groupType: 0}).then((res) => {
        const data = res.data.data.list;
        this.treeData = data;
        let treeDataOne = {
          companyId: "",
          createTime: "",
          groupName: "全部",
          id: "",
          remarks: "",
          sort: '',
          sumNum: res.data.data.sum,
          type: '',
        };
        this.treeData.unshift(treeDataOne);
        this.loading = false;
      });
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page, this.query);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page, this.query);
    },
    logSizeChange(pageSize) {
      this.logPage.pageSize = pageSize;
      this.serveLog(this.selectUserServeLog);
    },
    logCurrentChange(currentPage) {
      this.logPage.currentPage = currentPage;
      this.serveLog(this.selectUserServeLog);
    },
    onLoad(page, params = {}) {
      const {releaseTimeRange} = params;
      let paramsed = {
        current: page.currentPage,
        pageSize: page.pageSize,
        ...this.query
      };
      this.loading = true;
      getList(paramsed).then((res) => {
        const {total, size, current, records, page} = res.data.data
        this.dataSource = records;
        this.loading = false;
        this.page = {
          pageSize: size,
          currentPage: current,
          total: total,
        }
      });
    },
    serveLog(row) {
      console.log('服务日志', row)
      this.selectUserServeLog = row
      this.loadingLog = true
      getMainServeUserLog({
        idNumber: row.idNumber,
        current: this.logPage.currentPage,
        size: this.logPage.pageSize
      }).then(res => {
        this.loadingLog = false
        const {records, current, size, total} = res.data.data
        this.logDataSource = records
        this.innerDrawerLog = true
        this.logPage = {
          pageSize: size,
          currentPage: current,
          total: total,
        }
      })
    },
    async handleSubmitLog(row, done) {
      let params = {
        ...row,
        serveId: this.selectUserServeLog.serveId,
        serveUserId: this.selectUserServeLog.serveUserId,
        talentsId: this.selectUserServeLog.id,
        idNumber: this.selectUserServeLog.idNumber,
        toName: this.selectUserServeLog.name,
        fromName: this.userInfo.real_name
      }
      console.log(params)
      let resData = await addServeLog(params)
      done()
      if (resData.data.code === 200) {
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        this.innerDrawerAddLog = false
      }
    },
    async saveLog(row, index, done, loading) {
      let params = {
        ...row,
        serveId: this.selectUserServeLog.serveId,
        serveUserId: this.selectUserServeLog.serveUserId,
        talentsId: this.selectUserServeLog.id,
        idNumber: this.selectUserServeLog.idNumber,
        toName: this.selectUserServeLog.name,
        fromName: this.userInfo.real_name
      }
      console.log(params)
      let resData = await addServeLog(params)
      done()
      if (resData.data.code === 200) {
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        this.serveLog(this.selectUserServeLog)
      }
    },
    async saveUpdateLog(row, index, done, loading) {
      let params = {
        id: row.id,
        createTime: row.createTime,
        fromName: row.fromName,
        toName: row.toName,
        serveTheme: row.serveTheme,
        serveContent: row.serveContent,
        bak1: row.bak1,
      }
      let resData = await updateServeLog(params)
      done()
      if (resData.data.code === 200) {
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        this.serveLog(this.selectUserServeLog)
      }
    },
    removeLog(row, index, done, loading) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return removeServeLog({ids: row.id});
        })
        .then(() => {
          this.serveLog(this.selectUserServeLog)
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleCloseLog() {
      this.innerDrawerLog = false
    },
  }
}

</script>

<style lang="scss" scoped>


</style>
