<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"

        @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 { getServerList, allTalentsGroup,serveLogs } from "../../../../api/tenant/personnelServiceLog";
import {addServeLog, getMainServeUserLog, removeServeLog, updateServeLog} from "@/api/tenant/serve";
// import {cloneDeep} from "lodash";
import {serveTypeOptions} from "@/common/dic";

const page = {
  size: 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: {},
      query: {},
      groupId: '', // 人群id
      allTalentsGroupTree: [], // 人群数据
    }
  },
  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: "name",
            span: 24,

          },
          {
            label: "性别",
            prop: "aac004",
            type: 'select',
            searchLabelWidth: 80,
            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: "companyName",
            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: "groupName",
            type: "tree",
            multiple: false,
            dicData: this.allTalentsGroupTree,
            // dicUrl: "/api/jobslink-api/serve/allTalentsGroup",
            props: {
              label: "groupName",
              value: "id",
            },
            checkStrictly: true,
            span: 24,
            search: true,
            searchLabelWidth: 80,
            change: this.groupChange
          },
          {
            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: "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: "serveTotalCount",
            span: 24,
          },
          {
            label: "备注",
            prop: "remarks",
            type: "textarea",
            slot: true,
            hide: true,
            span: 24,
            maxlength: 100,
            showWordLimit: true,
          },
          {
            label: "日志时间",
            prop: "Time",
            search: true,
            type: 'date',
            searchRange: true,
            hide: true,
            display: false,
            searchLabelWidth: 80,
            minWidth: 100,
            searchSpan: 7,
            startPlaceholder: "日期开始范围",
            endPlaceholder: "日期结束范围",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            change: ({value}) => {
              if (value) {
                this.query.stime = value[0]
                this.query.etime = value[1]
              }
            }
          },
        ],
      }
    },
    logOption() {
      return {
        editBtn: false,
        delBtn: false,
        addBtn: false,
        viewBtn: false,
        border: true,
        menu: false,
        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: 'serveType',
          type: 'select',
          dicData: serveTypeOptions,
          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.getaAllTalentsGroup()
    this.onLoad(this.page, this.query)
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.crud.refreshTable()
    })
  },
  methods: {
// 人群的id
    deptChange({value, column}) {
      this.deptId = value
      console.log(value)
    },
    groupChange(value) {
      this.groupId = value
    },
    async getDept() {
      let params = {
        tenantId: '000000'
      }
      let resData = await getDeptMyTree(params)
      if (resData.data.code === 200) {
        this.depTree = resData.data.data
      }
    },
    async getaAllTalentsGroup() {

      let resData = await allTalentsGroup()
      if (resData.data.code === 200) {
        this.allTalentsGroupTree = 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) {
      let newObj = Object.assign({}, params);
      if (params.Time) {
        newObj.stime = params.Time[0]
        newObj.etime = params.Time[1]
        delete newObj.Time;
      }
      if (params.companyName) {
        newObj.deptId = params.companyName
        delete newObj.companyName;
      }
      if (params.groupName) {
        newObj.groupId = params.groupName
        delete newObj.groupName;
      }
      this.query = newObj;
      this.page.currentPage = 1;
      this.onLoad(this.page, newObj);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page, this.query);
    },
    sizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page, this.query);
    },
    logSizeChange(size) {
      this.logPage.size = size;
      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,
        size: page.size,
        ...this.query
      };
      this.loading = true;
      getServerList(paramsed).then((res) => {
        const {total, size, current, records, page} = res.data.data
        this.dataSource = records;
        this.loading = false;
        this.page = {
          size: size,
          currentPage: current,
          total: total,
        }
      });
    },
    serveLog(row) {
      this.selectUserServeLog = row
      this.loadingLog = true
      serveLogs({
        idNumber: row.idNumber,
        current: this.logPage.currentPage,
        size: this.logPage.size,
        groupId: row.groupId
      }).then(res => {
        this.loadingLog = false
        const {records, current, size, total} = res.data.data
        this.logDataSource = records
        this.innerDrawerLog = true
        this.logPage = {
          size: 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>
