<template>
  <div style="padding: 0 20px">

    <div ref="lxHeader">
      <lx-header icon="md-apps" text="档案管理" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
        <slot>
          <div style="display: flex;justify-content: flex-start;flex-wrap: wrap;">
            <Input v-model="select.keyword" style="width: 150px;margin-right: 10px;" placeholder="搜索姓名" />
            <el-select class='street' v-model="select.jiedao" placeholder="请选择街道" clearable>
              <el-option v-for="item in lists.streetList" :key="item.value" :label="item.value" :value="item.value">
              </el-option>
            </el-select>
            <el-select class='street' v-model="select.disabilityType" placeholder="请选择残疾类别" clearable>
              <el-option v-for="item in lists.disabilitytypeList" :key="item.value" :label="item.value"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select class='street' v-model="select.disabilityLevel" placeholder="请选择残疾等级" clearable>
              <el-option v-for="item in lists.disabilitylevelList" :key="item.value" :label="item.value"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select class='street' style='width:120px' v-model="select.link_tables[0]['year']" placeholder="请选择年份"
              clearable>
              <el-option v-for="item in [{label:2021,value:2021},{label:2022,value:2022},{label:2023,value:2023}]"
                :key="item.value" :label="item.value" :value="item.value">
              </el-option>
            </el-select>
            <el-select collapse-tags class='street' style='width:240px' v-model="select.link_tables[0]['tables']" multiple placeholder="请选择业务" clearable>
              <el-option v-for="item in lists.workflowList"
                :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>


            <Button type="primary" @click="getindex">查询</Button>
            <Button type="primary" style="margin-left: 10px;" @click="resetindex">重置</Button>
            <Button type="primary" style="margin-left: 10px;"
              @click="$refs['addRecord'].isShow = true,$refs['addRecord'].type = 'add'">添加</Button>
            <Button type="primary" style="margin-left: 10px;" @click="$refs['imports'].show()">导入</Button>
            <Button type="primary" style="margin-left: 10px;"
              @click="exportExcel(new Date().getTime().toString())">导出</Button>
          </div>
        </slot>
      </lx-header>
    </div>

    <xy-table :list="list" :total="total" @pageSizeChange="e => select.pageSize = e" @pageIndexChange="pageChange"
      :table-item="table">
      <template v-slot:btns>
        <el-table-column fixed="right" label="操作" width="260" header-align="center">
          <template slot-scope="scope">
            <Button type="primary" size="small" @click="editorRecord(scope.row.id,'editor')">编辑</Button>
            <Button type="primary" size="small" style="margin-left: 10px;"
              @click="editorView(scope.row.id,'add')">访视</Button>
            <Button type="primary" size="small" style="margin-left: 10px;" @click="showInfo(scope.row.id)">视图</Button>
            <Poptip transfer confirm title="确认要删除吗？" @on-ok="deleteRecord(scope.row)">
              <Button type="primary" style="margin-left: 10px;" size="small" ghost>删除</Button>
            </Poptip>
          </template>
        </el-table-column>
      </template>
    </xy-table>
    <addRecord ref="addRecord" @refresh="getindex"></addRecord>
    <addViewRecord ref="addViewRecord" @refresh="getindex"></addViewRecord>
    <imports :table-name="customForm.tableName" :form-info="importForm" ref="imports" @refresh="getindex"></imports>

  </div>
</template>

<script>
  import {
    index,
    destroy
  } from "@/api/system/baseForm.js"
  import addRecord from "./components/addRecord.vue"
  import addViewRecord from "@/views/viewrecords/components/addViewRecord.vue"
  import {
    Message
  } from 'element-ui'
  import imports from "@/views/component/imports.vue"
  import * as XLSX from "xlsx";
  import {
    saveAs
  } from "file-saver";
  import {
    index as fieldIndex
  } from "@/api/system/customFormField";
  import {
    getparameter
  } from "@/api/system/dictionary";
  export default {
    components: {
      addRecord,
      addViewRecord,
      imports
    },
    data() {
      return {

        select: {
          pageSize: 40,
          pageIndex: 1,
          keyword: "",
          jiedao: '',
          disabilityLevel: "",
          disabilityType: "",
          link_tables: [{
            'year': '',
            "tables": []
          }]
        },
        lists: {
          disabilitytypeList: [],
          disabilitylevelList: [],
          streetList: [],
          workflowList: [{
            label: '机动轮椅车燃油补贴',
            value: 'fuels'
          }, {
            label: '无障碍改造',
            value: 'reforms'
          }, {
            label: '免费服药',
            value: 'medicines'
          }, {
            label: '儿童康复',
            value: 'childrens'
          }, {
            label: '辅具适配',
            value: 'assists'
          }, {
            label: '社区康复',
            value: 'communities'
          }, {
            label: '教育专项补贴',
            value: 'educations'
          }, {
            label: '托养',
            value: 'raises'
          }, {
            label: '自主创业补贴',
            value: 'starts_subsidys'
          }, {
            label: '自主创业经营场地租金补贴',
            value: 'starts_addresses'
          }, {
            label: '两项补贴',
            value: 'doubles'
          }, {
            label: '残疾人证申请',
            value: 'disabilities'
          }, {
            label: '培训记录',
            value: 'trains'
          }, {
            label: '商业保险',
            value: 'insures'
          }, {
            label: '已就业人员',
            value: 'jobs'
          }, {
            label: '死亡注销',
            value: 'cancels'
          }]
        },
        customForm: {
          customFormId: 1,
          tableName: "records"
        },
        form: [],
        importForm: [],
        exportForm: [],
        total: 0,
        list: [],
        table: [{
            label: '序号',
            type: 'index',
            fixed: 'left',
            width: 60
          },
          // {
          //   label: "所属街道",
          //   width: 120,
          //   prop: 'street',
          //   align: 'center'
          // },
          {
            label: "姓名",
            width: 120,
            prop: 'name',
            align: 'center',
            fixed: 'left'
          },
          {
            label: "性别",
            width: 80,
            prop: 'sex',
            align: 'center',
          },
          {
            label: "年龄",
            width: 80,
            prop: 'idcard',
            align: 'center',
            formatter: (cell, data, value) => {
              if(value){
                 return this.getName(value)
              }else{
                return ''
              }
             
            }
          },
          // {
          //   label: "身份证号",
          //   width: 180,
          //   prop: 'idcard',
          //   align: 'center'
          // },
          // {
          //   label: "联系电话",
          //   width: 120,
          //   prop: 'mobile',
          //   align: 'center'
          // },
          // {
          //   label: "固话",
          //   width: 120,
          //   prop: 'telephone',
          //   align: 'center'
          // },
          // {
          //   label: "残疾证号",
          //   width: 180,
          //   prop: 'number',
          //   align: 'center'
          // },
          {
            label: "残疾类别",
            width: 80,
            prop: 'disabilitytype',
            align: 'center'
          },
          {
            label: "残疾等级",
            width: 80,
            prop: 'disabilitylevel',
            align: 'center'
          },
          {
            label: "户籍地址",
            // width: 240,
            prop: 'address',
            align: 'left',
            formatter: (cell, data, value) => {
              if(value){
                return value.indexOf('江苏省常州市金坛区') > -1 ? value.replace('江苏省常州市金坛区', '') : value

              }else {
                return ''
              }
            }
          },
          // {
          //   label: "有效期至",
          //   width: 180,
          //   prop: 'validity',
          //   align: 'center'
          // },

          // {
          //   label: "现居住地",
          //   width: 240,
          //   prop: 'reside',
          //   align: 'left'
          // }
        ]
      }
    },
    methods: {
      showInfo(id) {
        this.$router.push({
          path: "/record/personinfo",
          query: {
            id: id
          }
        })
      },
      resetindex() {
        this.select = {
          pageSize: 40,
          pageIndex: 1,
          keyword: "",
          jiedao: '',
          disabilityLevel: "",
          disabilityType: "",
          link_tables: [{
            'year': '',
            "tables": []
          }]
        }
        this.getindex()
      },
      async getindex() {
        const res = await index({
          page_size: this.select.pageSize,
          page: this.select.pageIndex,
          table_name: this.customForm.tableName,
          link_tables: this.select.link_tables,
          // link_tables[0]['year']:'2023',
          show_relation: ['admin', 'department'],
          filter: [{
            "key": "name",
            "op": "like",
            "value": this.select.keyword
          }, {
            "key": "jiedao",
            "op": "eq",
            "value": this.select.jiedao
          }, {
            "key": "disabilitytype",
            "op": "eq",
            "value": this.select.disabilityType
          }, {
            "key": "disabilitylevel",
            "op": "eq",
            "value": this.select.disabilityLevel
          }],
        })
        this.list = res.data
        this.total = res.total
      },

      pageChange(e) {
        this.select.pageIndex = e
        this.getindex()
      },
      editorRecord(id, type) {
        this.$refs['addRecord'].id = id
        this.$refs['addRecord'].isShow = true
        this.$refs['addRecord'].type = type
      },
      editorView(id, type) {
        console.log(id, type)
        this.$refs['addViewRecord'].person_id = id
        this.$refs['addViewRecord'].isShow = true
        this.$refs['addViewRecord'].type = type

      },
      deleteRecord(row) {
        destroy({
          id: row.id,
          table_name: this.customForm.tableName
        }).then(res => {
          Message({
            type: 'success',
            message: '删除成功'
          })
          this.getindex()
        })
      },
      getName(iden) {
        let val = iden.length;
        let myDate = new Date();
        let month = myDate.getMonth() + 1;
        let day = myDate.getDate();
        let age = 0;

        if (val === 18) {
          age = myDate.getFullYear() - iden.substring(6, 10) - 1;

          if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++;

        }
        if (val === 15) {
          age = myDate.getFullYear() - iden.substring(6, 8) - 1901;

          if (iden.substring(8, 10) < month || iden.substring(8, 10) == month && iden.substring(10, 12) <= day) age++;
        }

        return age
      },
      // 获取表信息
      async getField() {
        // console.log(this.$route.meta.params, "---", this.$route)
        // return
        // if (this.$route.meta.params?.custom_form) {
        //   let decode = decodeURIComponent(this.$route.meta.params?.custom_form)
        //   try {
        //     let custom_form = JSON.parse(decode)
        //     this.customForm.customFormId = custom_form.custom_form_id
        //     this.customForm.tableName = custom_form.table_name
        //     console.log("123", this.customForm)
        //     // this.select.table_name = custom_form.table_name
        //   } catch (err) {
        //     console.warn(err)
        //   }
        // }
        const res = await fieldIndex({
          page: 1,
          page_size: 999,
          custom_form_id: this.customForm.customFormId,
          sort_name: 'sort',
          sort_type: 'asc',
        })
        if (res.data && res.data instanceof Array) {
          res.data.forEach(i => {
            if (i.field) {
              if (
                (i.edit_input === "checkbox" || i.edit_input === "radio" || i.edit_input === "select") &&
                i.parameter_id
              ) {
                getparameter({
                  id: i.parameter_id
                }).then((res) => {
                  i._paramters = res.detail ?? [];
                });
              }
              if (
                (i.edit_input === "checkbox" || i.edit_input === "radio" || i.edit_input === "select") &&
                i.link_table_name
              ) {
                index({
                  page: 1,
                  page_size: 999,
                  table_name: i.link_table_name,
                }).then((res) => {
                  i._paramters = res.data ?? [];
                });
              }
            }
          })
        }
        this.form = res.data
        this.importForm = this.form
          ?.filter((i) => i.form_show && i.list_show)
          .map((i) => {
            return i
          })
        this.exportForm = this.form
          ?.filter((i) => i.list_show)
          .map((i) => {
            return i
          })
      },
      async exportExcel(sheetName) {
        const res = await index(Object.assign(this.select, {
          page: 1,
          page_size: 99999,
          table_name: this.customForm.tableName
        }))
        if (res.data) {
          let headers = this.exportForm.map(i => {
            return {
              key: i.field,
              title: i.name
            }
          })
          const data = res.data.map(row => headers.map(header => row[header.key]));
          data.unshift(headers.map(header => header.title));
          const wb = XLSX.utils.book_new();
          const ws = XLSX.utils.aoa_to_sheet(data);
          XLSX.utils.book_append_sheet(wb, ws, sheetName);
          const wbout = XLSX.write(wb, {
            bookType: 'xlsx',
            bookSST: true,
            type: 'array'
          });
          saveAs(new Blob([wbout], {
            type: 'application/octet-stream'
          }), `${sheetName}.xlsx`);
        }
      },
      async getLabel() {
        let numbers = {
          number: ['streetList', 'disabilitylevelList', 'disabilitytypeList']
        }
        const res = await getparameter(numbers);
        for (var k of res) {
          for (var m in this.lists) {
            if (m == k.number) {
              this.lists[m] = k.detail
            }
          }
        }
      },
    },
    mounted() {
      this.getindex()
      this.getField()
      this.getLabel()

    }

  }
</script>

<style scoped>
  .street {
    margin-right: 10px;
    width: 150px
  }

  /deep/ .street .el-input__inner {
    height: 32px;
  }

  /deep/ .street .el-select__caret {
    line-height: 32px;
  }
</style>
