<template>
  <div>
    <div>
      <div ref="lxHeader">
        <LxHeader style="margin-bottom: 10px; border: 0px; margin-top: 15px">
          <div slot="content"></div>
          <slot>
            <header-content :auths="auths_auth_mixin">
              <template #search>
                <div>
                  <div style="margin-bottom:15px">
                    <span style="margin-right:15px;display: inline-block;">年度 </span>
                    <el-radio-group v-model="select.year" @change="changeYear">
                      <el-radio style="margin-right:5px" v-for="item in yearList" border
                        :label="item">{{item}}</el-radio>
                    </el-radio-group>
                  </div>
                  <div>
                    <span style="margin-right:15px;display: inline-block;">类型 </span>
                    <el-radio-group @change="changeCategoryType" v-model="select.category_type_id">
                      <el-radio style="margin-right:5px" v-for="item in categoryTypeList" border
                        :label="item.id">{{item.title}}</el-radio>
                    </el-radio-group>
                  </div>
                  <!-- <el-date-picker size="small" style="width: 110px;" placeholder="请选择日期" value-format="yyyy" v-model="select.year" type="year"></el-date-picker> -->
                  <!-- <Button
                    style="margin-left: 10px;"
                    type="primary"
                    @click="getList"
                  >查询</Button> -->
                </div>
              </template>
              <!-- <template #create>
                <Button type="primary" @click="$refs['create'].setType('add'),$refs['create'].show()">新增</Button>
              </template>
              <template #setting>
                <Button type="primary" :ghost="isStartSelect" @click="isStartSelect = !isStartSelect">设置清单类型</Button>
              </template> -->
            </header-content>
          </slot>
        </LxHeader>
      </div>
    </div>

    <div>
      <div  style="margin-bottom:15px;">
        <el-button v-if="select.category_type_id" @click="$refs['create'].setType('add'),
        $refs['create'].setForm('type_id', select.category_type_id),
        $refs['create'].setForm('year', select.year.toString()),
        $refs['create'].show()" plain>新建{{select.year}}年{{select.categoryTypeName}}清单</el-button>
      </div>
      <xy-table ref="xyTable" :is-page="false" :list="list" res-prop="" :indent="20" :row-key="row => row._index"
        :table-item="table" :auths="auths_auth_mixin" :req-opt="select" :destroy-action="destroy" @editor="row => {
                  $refs['create'].setId(row.id);
                  $refs['create'].setType('editor');
                  $refs['create'].show();
                }" @destroyed="getList">
                <template v-slot:btns>
                  <el-table-column align='center' fixed="right" label="操作" width="220" header-align="center">
                    <template slot="header" slot-scope="scope">
                      <el-button
                        size="mini" @click="">整体克隆</el-button>
                    </template>
                    <template slot-scope="scope">
                      <div  style="display: flex;">
                        <Button v-if="scope.row._type !== 'type'" size="small" type="primary" @click="$refs['create'].setId(scope.row.id),
                                $refs['create'].setType('editor'),
                                $refs['create'].show();">编辑</Button>
                        <el-popover width="180" v-if="scope.row._type !== 'type'" :ref="`${scope.row.id}-${scope.$index}`" trigger="hover">
                          <template>
                            <div>
                              <p style="padding-bottom: 10px;">确定要删除吗？</p>
                              <div style="text-align: right;margin: 0;">
                                <el-button size="mini" type="text" @click="$refs[`${scope.row.id}-${scope.$index}`].doClose()">取消</el-button>
                                <el-button type="primary" size="mini"
                                  @click="$refs['xyTable'].deleteClick(scope.row, 'delete')">确定</el-button>
                              </div>
                            </div>
                          </template>
                          <template #reference>
                            <div style="margin-right: 6px;height: 100%;width: 100%;">
                              <Button type="error" size="small" @click="$refs[`${scope.row.id}-${scope.$index}`].doShow()">
                                删除
                              </Button>
                            </div>
                          </template>
                        </el-popover>
                        <Button size="small" type="primary" @click="createChild(scope.row)">子栏目</Button>

                      </div>

                    </template>
                  </el-table-column>
                </template>







      </xy-table>
    </div>


    <create ref="create" :options="list" @refresh="getList"></create>
    <categorySetting ref="categorySetting"></categorySetting>
    <createRules ref="createRules"  @refresh="getList"></createRules>
  </div>
</template>

<script>
  import {
    index,
    destroy,
    categoryYears,
    categoryTypes
  } from "@/api/category"
  import {
    authMixin
  } from "@/mixin/authMixin";
  import headerContent from "@/components/LxHeader/XyContent.vue";
  import LxHeader from "@/components/LxHeader/index.vue";
  import create from "./component/create.vue";
  import categorySetting from "./component/categorySetting.vue";
  import createRules from "./component/createRules.vue";

  export default {
    mixins: [authMixin],
    components: {
      categorySetting,
      headerContent,
      LxHeader,
      create,
      createRules
    },
    data() {
      return {
        provideOptions: [],
        yearList: [],
        categoryTypeList:[],
        select: {
          year: '',
          category_type_id:'',
          categoryTypeName:''
        },
        isStartSelect: false,
        list: [],
        table: [
          // {
          //   type: "selection",
          //   width: 48,
          //   selectable: row => {
          //     return row._type === 'type' ? false : this.isStartSelect;
          //   }
          // },
          {
            type: "",
            label: "",
            prop: "index",
            fixed:'left',
            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: "预警规则",
              fixed:"right",
              customFn: row => {
                return(<div>
                  <el-button plain type='primary' size="mini"
                  on = {
                    {
                      ['click']: (e) => {
                        this.createRules(row)
                      }
                    }
                  }
                  >规则设置</el-button>
                  <div>{
                    row.rules.map(item=>{
                      return(<div>{item.start_at}~{item.end_at}不少于{item.quantity}条</div>)
                    })
                  }</div>
                </div>)
              }
            },
            {
              prop: "myindex",
              label: "排序",

            }]
            }
          },
          created() {
            this.getPastYears()
            this.getList()
            // this.yearList = this.getPastYears(5)
            this.getCategoryType()
            // this.select.year = this.$moment().format('YYYY')
          },
          methods: {
            index,
            destroy,
            getCategoryType(){
              categoryTypes().then(res=>{
                this.categoryTypeList = res
                this.select.category_type_id = res.length>0?res[0].id:''
                this.select.categoryTypeName = res.length>0?res[0].title:''

              })
            },
            changeYear(e){
              if(e){
                this.getList()
              }
            },
            changeCategoryType(e){
              if(e){
                this.categoryTypeList.map(item=>{
                  if(item.id===e){
                    this.select.categoryTypeName = item.title
                  }
                })
                this.getList()
              }

            },
            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)
                  // item._index = pid ? (index+1) : (index + 1)
                }
                if (item.children instanceof Array && item.children.length > 0) {
                  this.formatList(item.children, item._index ? item._index : false)
                }
              })
            },
            getPastYears(years) {
              categoryYears().then(res=>{
                this.yearList = res.years
                this.select.year = res.selected_year
              })
            },
            async getList() {
              let res = await index({
                year:this.select.year,
                category_type_id:this.select.category_type_id
              });
              this.formatList(res);
              this.list = res;
            },

            createChild(row) {
              let category_type_id = this.select.category_type_id
              if(row.type_id){
                category_type_id = row.type_id
              }
              if (row._type === 'type') {
                this.$refs['create'].setForm('type_id', category_type_id);
                this.$refs['create'].setForm('pid', 0);
                this.$refs['create'].setForm('year', this.select.year.toString());
                this.$refs['create'].setType('add');
                this.$refs['create'].show();
              } else {
                this.$refs['create'].setForm('type_id', category_type_id);
                this.$refs['create'].setForm('pid', row.id);
                this.$refs['create'].setForm('year', this.select.year.toString());
                this.$refs['create'].setType('add');
                this.$refs['create'].show();
              }
            },
            createRules(row){
              console.log(row)
              if(row._type==='type'){
                this.$refs['createRules'].category_id = row._id
              }else{
                this.$refs['createRules'].category_id = row.id
              }

              this.$refs['createRules'].title = row.title;
              this.$refs['createRules'].isShow = true;
            }
          },
          computed: {},
          watch: {
            isStartSelect(newVal) {
              const selections = this.$refs['xyTable'].getSelection()
              if (!newVal && selections.length > 0) {
                this.$refs['categorySetting'].setSelections(selections)
                this.$refs['categorySetting'].show()
              }
            }
          }
        }
</script>

<style scoped lang="scss">
  a {
    color: $primaryColor;
    text-decoration: none;
    transition: all 0.2s;
  }

  a:hover {
    color: $primaryColor;
    text-decoration: underline;
  }
</style>
