<template>
  <div class="card">
    <xy-table ref="xyTable"
              height="100%"
              :isHandlerKey="false"
              :is-page="false"
              :list="categories"
              res-prop=""
              :indent="20"
              :row-key="row => row._index"
              :table-item="table"
              :auths="[]">
    </xy-table>

    <el-drawer title="填报清单" :visible.sync="isShowDrawer" position="rtl" size="560px">
      <div style="padding: 20px 40px;">
        <el-form class="form" ref="elForm" :model="form" :rules="rules" label-width="80px" size="small">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="内容" required prop="content">
            <el-input type="textarea" :autosize="{ minRows:2 }" v-model="form.content"></el-input>
          </el-form-item>
          <el-form-item label="附件" prop="files">
            <el-upload
              class="upload-demo"
              :action="action"
              multiple
              :limit="10"
              :before-upload="beforeUpload"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="所属月份" required prop="belongs_year_month">
            <el-date-picker placeholder="请选择所属月份" type="month" value-format="yyyy-MM" v-model="form.belongs_year_month"></el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit">立即创建</el-button>
            <el-button @click="isShowDrawer = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { category, recordStore } from "@/api/h5/form";
export default {
  data() {
    return {
      isShowDrawer: false,
      fileList: [],
      action: process.env.VUE_APP_UPLOAD_API,
      select: {
        year: ""
      },
      categories: [],
      table: [
        {
          type: "",
          label: "",
          prop: "index",
          customFn:row => {
            return row._type === 'type' ? row._text : row._index;
          }
        },
        {
          prop: "title",
          label: "清单类型名称",
          align: "left",
          customFn:row => {
            return row._type === 'type' ? (<span><i style="padding: 0 8px;color: rgb(239, 216, 117);" class="el-icon-folder-opened"></i><span>{row.title}</span></span>) : (
              <span><i style="padding: 0 8px;" class="el-icon-document"></i><span>{row.title}</span></span>)
          }
        },
        {
          prop: "records_count",
          label: "填报数量",
          customFn:row => {
            if (!row.children?.length) {
              return (<span>{row.records_count}</span>)
            }
          }
        },
        {
          prop: "btns",
          label: "填报",
          fixed: "right",
          width: 80,
          customFn: row => {
            if (!row.children?.length) {
              return (
                <Button
                  size="small"
                  type="primary"
                  icon="ios-create"
                  on={
                    {
                      ['click']:_ => {
                        this.isShowDrawer = true;
                        this.form.category_id = row.id;
                      }
                    }
                }>
                  填报
                </Button>
              )
            }
          }
        }
      ],
      form: {
        category_id: "",
        title: "",
        content: "",
        files: "",
        belongs_year_month: "",
        myindex: ""
      },
      rules: {
        content: [
          { required: true, message: "请填写内容" }
        ],
        belongs_year_month: [
          { required: true, message: "请选择所属月份" }
        ]
      }
    }
  },
  methods: {
    async getList () {
      let res = await category(this.select);
      this.formatList(res);
      this.list = res;
    },

    beforeUpload (file) {
      if ((file.size / 1000) > (20 * 1024)) {
        this.$message({
          type: "warning",
          message: "上传大小超过20Mb！",
        });
        return false;
      }
    },

    toChineseNum(number) {
      const chineseNum = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
      const chineseUnit = ["", "十", "百", "千", "万", "亿"];
      let numStr = number.toString();
      let len = numStr.length;
      let str = "";
      for (let i = 0; i < len; i++) {
        str += chineseNum[parseInt(numStr[i])] + chineseUnit[len - 1 - i];
      }
      str = str.replace(/零[十百千]/g, "零");
      str = str.replace(/零+/g, "零");
      str = str.replace(/^零+/, "");
      str = str.replace(/零+$/, "");
      if (str[str.length - 1] === "零") {
        str = str.slice(0, -1);
      }
      return str
    },

    formatList (data=[],pid) {
      data.forEach((item,index) => {
        if (item.hasOwnProperty('categories_tree')) {
          item._id = item.id
          delete item.id;
          item._disabled = true
          item._type = 'type'
          item.children = item.categories_tree
          item._text = this.toChineseNum(index+1)
        } else {
          item._type = 'doc'
          item._index = pid ? `${pid}-${index+1}` : (index+1)
        }
        if (item.children instanceof Array && item.children.length > 0) {
          this.formatList(item.children,item._index ? item._index : false)
        }
      })
    },

    async getCategories () {
      const res = await category(this.select,false)
      this.formatList(res)
      this.categories = res
    },

    onSubmit () {
      this.$refs['elForm'].validate(res => {
        if (res) {
          this.form.files = this.fileList.map(i => i.response.id).toString()
          recordStore(this.form).then(res => {
            this.$message({
              type: "success",
              message: "填报成功"
            })
          })
        }
      })
    }
  },
  computed: {},
  created() {
    this.getCategories()
  }
}
</script>

<style lang="scss">
.el-cascader-node__label {
  max-width: 300px;
}
</style>
<style scoped lang="scss">
.card {
  height: 100%;

  padding: 40px;
}
::v-deep .table-tree {
  height: 100%;
}
</style>
