<template>
  <template-page ref="pageRef" :get-list="getList" :table-attributes="tableAttributes" :table-events="tableEvents"
    :options-evens-group="optionsEvensGroup" :moreParameters="moreParameters" :column-parsing="columnParsing"
    :operation="operation" :exportList="exportList">
    <el-dialog title="" width="1165px" custom-class="diy-dialog" append-to-body :modal="true" :visible.sync="formDialog"
      :show-close="true" :close-on-click-modal="false" :modal-append-to-body="false" :before-close="formCancel">
      <zj-form-container ref="formRef" :form-data="formData" :styleSwitch="false">
        <zj-form-module :title="formDialogTitles[formDialogType]" label-width="100px" :showPackUp="false"
          :form-data="formData" :form-items="formItems">
        </zj-form-module>
      </zj-form-container>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="formCancel">取 消</el-button>
        <el-button size="mini" @click="formConfirm" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="" width="300px" custom-class="diy-dialog" append-to-body :modal="true" :visible.sync="formDialog2"
      :show-close="true" :close-on-click-modal="false" :modal-append-to-body="false" :before-close="formCancel2">
      <zj-form-container ref="formRef2" :form-data="formData2" :styleSwitch="false">
        <zj-form-module title="地区选择" label-width="0px" :showPackUp="false" :form-data="formData2"
          :form-items="formItems2">
        </zj-form-module>
      </zj-form-container>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="formCancel2">取 消</el-button>
        <el-button size="mini" @click="formConfirm2" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import { required, mobileRequired, mobile } from '@/components/template/rules_verify.js'
import { freightListPageV2, freightPageExport, deleteFreight, addOrEditFreight, getFreightDetail, getRegionTree, changeFreightStatus } from "@/api/freight";
export default {
  components: { TemplatePage },
  mixins: [import_mixin],
  data() {
    return {
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新建',
              isRole: true,
              click: this.addData
            }
          ],
        ],
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ["新增", "编辑"],
      formDialog: false,
      formData: {
        name: '',
        freightTemplateDetails: []
      },
      formDialog2: false,
      formData2: {},
      regionTree: []
    }
  },
  computed: {
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return [{
        md: 24,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入' },
        formItemAttributes: {
          label: '仓储名称',
          prop: 'name',
          rules: [...required]
        }
      }, {
        md: 24,
        isShow: true,
        name: 'slot-component',
        formItemAttributes: {
          label: '配送区域',
          prop: '',
          rules: [...required]
        },
        render: (h, { props, onInput }) => {
          var { value } = props
          return (
            <div>
              <div><el-button type="primary" size="mini" onClick={() => {
                this.openForm2()
              }}>添加地区</el-button></div>
              <zj-table
                columns={[
                  {
                    columnAttributes: {
                      label: '省',
                      prop: 'province',
                      width: "140px",
                    }
                  },
                  {
                    columnAttributes: {
                      label: '市',
                      prop: 'city',
                      width: "140px",
                    }
                  },
                  {
                    columnAttributes: {
                      label: '首件(个)',
                      prop: 'firstLimit',
                      width: "160px",
                      'render-header': (h, obj) => this.renderHeader(h, obj, 'firstLimit')
                    },
                    render: (h, { row, column, index }) => {
                      return <el-form-item prop={`freightTemplateDetails.${index}.${column.columnAttributes.prop}`} rules={[...required]}>
                        <el-input type="number" value={this.formData.freightTemplateDetails[index][column.columnAttributes.prop]} onInput={(val) => { this.formData.freightTemplateDetails[index][column.columnAttributes.prop] = val }}></el-input>
                      </el-form-item>
                    }
                  },
                  {
                    columnAttributes: {
                      label: '运费(元)',
                      prop: 'firstAmount',
                      width: "160px",
                      'render-header': (h, obj) => this.renderHeader(h, obj, 'firstAmount')
                    },
                    render: (h, { row, column, index }) => {
                      return <el-form-item prop={`freightTemplateDetails.${index}.${column.columnAttributes.prop}`} rules={[...required]}>
                        <el-input type="number" value={this.formData.freightTemplateDetails[index][column.columnAttributes.prop]} onInput={(val) => { this.formData.freightTemplateDetails[index][column.columnAttributes.prop] = val }}></el-input>
                      </el-form-item>
                    }
                  },
                  {
                    columnAttributes: {
                      label: '续件(个)',
                      prop: 'continuousLimit',
                      width: "160px",
                      'render-header': (h, obj) => this.renderHeader(h, obj, 'continuousLimit')
                    },
                    render: (h, { row, column, index }) => {
                      return <el-form-item prop={`freightTemplateDetails.${index}.${column.columnAttributes.prop}`} rules={[...required]}>
                        <el-input type="number" value={this.formData.freightTemplateDetails[index][column.columnAttributes.prop]} onInput={(val) => { this.formData.freightTemplateDetails[index][column.columnAttributes.prop] = val }}></el-input>
                      </el-form-item>
                    }
                  },
                  {
                    columnAttributes: {
                      label: '续费(元)',
                      prop: 'continuousAmount',
                      width: "160px",
                      'render-header': (h, obj) => this.renderHeader(h, obj, 'continuousAmount')
                    },
                    render: (h, { row, column, index }) => {
                      return <el-form-item prop={`freightTemplateDetails.${index}.${column.columnAttributes.prop}`} rules={[...required]}>
                        <el-input type="number" value={this.formData.freightTemplateDetails[index][column.columnAttributes.prop]} onInput={(val) => { this.formData.freightTemplateDetails[index][column.columnAttributes.prop] = val }}></el-input>
                      </el-form-item>
                    }
                  },
                  {
                    columnAttributes: {
                      label: '操作',
                      prop: '',
                      width: "80px"
                    },
                    render: (h, { row, column, index }) => {
                      return <el-button size="mini" type="text" onClick={() => {
                        this.formData.freightTemplateDetails.splice(index, 1)
                      }}>删除</el-button>
                    }
                  }
                ]}
                tableData={this.formData.freightTemplateDetails}
                tableAttributes={{
                  size: 'mini',
                  border: true,
                }} />
            </div>
          )
        }
      }]
    },
    formItems2() {
      return [{
        md: 24,
        isShow: true,
        name: 'el-tree',
        attributes: {
          style: "max-height: 400px; overflow-y: scroll;",
          placeholder: '请输入', data: this.regionTree, 'show-checkbox': true, 'node-key': "id", props: {
            children: 'child',
            label: 'name'
          }
        },
        formItemAttributes: {
          label: '',
          prop: 'val',
          rules: [...required]
        }
      }]
    }
  },
  methods: {
    // 列表请求函数
    getList: freightListPageV2,
    // 列表导出函数
    exportList: freightPageExport,
    // 表格列解析渲染数据更改
    columnParsing(defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    // 表格操作列
    operation(h, { row, index, column }) {
      return (
        <div class='operation-btns'>
          <el-button type="text" onClick={() => {
            getFreightDetail({ freightTemplateId: row.freightTemplateId }).then(res => {
              Object.assign(this.formData, res.data)
              this.formDialogType = 1
              this.openForm()
            })
          }}>编辑</el-button>
          {row.status ? <el-popconfirm style="margin-right: 10px;" title="确定禁用吗？"
            onConfirm={() => {
              changeFreightStatus({ freightTemplateId: row.freightTemplateId, status: false }).then(res => {
                this.$message({ type: 'success', message: '禁用成功!' })
                this.$refs.pageRef.refreshList()
              })
            }}>
            <el-button slot="reference" type="text">禁用</el-button>
          </el-popconfirm> : <el-popconfirm style="margin-right: 10px;" title="确定启用吗？"
            onConfirm={() => {
              changeFreightStatus({ freightTemplateId: row.freightTemplateId, status: true }).then(res => {
                this.$message({ type: 'success', message: '启用成功!' })
                this.$refs.pageRef.refreshList()
              })
            }}>
            <el-button slot="reference" type="text">启用</el-button>
          </el-popconfirm>}
          <el-popconfirm
            title="确定删除吗？"
            onConfirm={() => {
              deleteFreight({ freightTemplateId: row.freightTemplateId }).then(() => {
                this.$message({ type: 'success', message: '删除成功!' })
                this.$refs.pageRef.refreshList()
              })
            }}
          >
            <el-button type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </div>
      )
    },
    addData() {
      this.formDialogType = 0
      this.openForm()
    },
    openForm() {
      this.formDialog = true;
    },
    formCancel() {
      this.$refs.formRef.$refs.inlineForm.clearValidate()
      this.$data.formData = this.$options.data().formData
      this.formDialog = false
    },
    formConfirm() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          addOrEditFreight(this.formData).then(res => {
            this.$message({ type: 'success', message: `${this.formDialogTitles[this.formDialogType]}成功!` })
            this.formCancel()
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },
    renderHeader(h, { column, $index }, type) {
      let that = this;
      return h(
        'div',
        [
          h('span', column.label),
          h('el-button', {
            props: {
              type: 'text',
              size: 'small',
            },
            style: 'color:#409EFF; margin-left:5px;',
            on: {
              click: function () {
                that.changeInput(type);
              }
            }
          }, '统一修改')
        ],
      )
    },
    changeInput(type) {
      const typeMap = {
        firstLimit: '首件',
        firstAmount: '运费',
        continuousLimit: '续件',
        continuousAmount: '续费'
      }
      this.$prompt('请输入' + typeMap[type], '编辑', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: function (value) {
          if (!value) return '请输入' + typeMap[type]
        },
      }).then(({ value }) => {
        this.formData.freightTemplateDetails.forEach(item => {
          item[type] = value;
        })
      }).catch(() => { });
    },
    openForm2() {
      getRegionTree().then((res) => {
        this.regionTree = res.data
        this.regionTree.forEach(value => {
          value.child.forEach(childValue => {
            delete childValue.child
          })
        })
        this.formDialog2 = true;
      })
    },
    formCancel2() {
      this.$refs.formRef2.$refs.inlineForm.clearValidate()
      this.$data.formData2 = this.$options.data().formData2
      this.formDialog2 = false
    },
    formConfirm2() {
      var tree = (function getEl(arr) {
        var data
        for (var item of arr) {
          if (item.$el.className === "el-tree") {
            return item
          } else if (item.$children && item.$children.length) {
            data = getEl(item.$children)
          }
        }
        if (data) {
          return data
        }
      })(this.$refs.formRef2.$children)
      tree.getCheckedNodes(true, false).forEach(value => {
        let province = value.parentName;
        let city = value.name;
        let exist = this.formData.freightTemplateDetails.find((obj) => {
          return obj.province === province && obj.city === city
        })
        if (!exist) {
          this.formData.freightTemplateDetails.push({
            province: province,
            city: city,
            firstLimit: 1,
            firstAmount: 1,
            continuousLimit: 1,
            continuousAmount: 1
          })
        }
      })
      this.formCancel2()
    },
  }
}
</script>

<style lang="scss" scoped></style>
