<template>
  <div>
    <!-- <p-button type="primary"
              @click="新增">
      Open Modal
    </p-button> -->
    <p-modal
      title="新增"
      :visible="visibleAdds"
      :enlargeable="true"
      :draggable="true"
      width="80%"
      @ok="handleOk"
      @cancel="handleCancel"
      :footer="null"
      @enlargeChange="enlargeChange"
    >
      <!-- 步骤条 -->
      <div>
        <p-steps :current="current">
          <p-step v-for="item in steps" :key="item.title" :title="item.title" />
        </p-steps>
        <div style="background-color: rgba(0, 0, 0, 0.05); width: 100%; height: 1px; margin: 2em 0"></div>
        <!-- 第一步 -->
        <div v-if="current == 0">
          <p-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" @submit="handleSubmit">
            <p-form-item label="权限名称">
              <p-input v-decorator="['name', { rules: [{ required: true, message: '该项不能为空！' }] }]" />
            </p-form-item>
            <p-form-item label="权限类别">
              <p-select disabled default-value="1" :options="options" />
            </p-form-item>
            <!-- <p-form-item  label="所属组织">
					<p-tree-select v-model="value"
					                 style="width: 100%"
					                 :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
					                 :tree-data="treeData"
					                 placeholder="Please select"
					                 tree-default-expand-all>
					</p-tree-select>
				</p-form-item> -->
            <p-form-item label="是否启用">
              <p-checkbox :checked="enabled" @change="onChange">
                <!-- Checkbox -->
              </p-checkbox>
            </p-form-item>
            <p-form-item label="权限描述">
              <p-textarea
                allow-clear
                :rows="6"
                v-decorator="['remark', { rules: [{ required: false, message: '该项不能为空！' }] }]"
              />
            </p-form-item>
            <!-- <p-form-item :wrapper-col="{ span: 12, offset: 5 }">
				      <p-button type="primary" html-type="submit">
				        Submit
				      </p-button>
				</p-form-item> -->
          </p-form>
        </div>
        <!-- 第二步 -->
        <div v-else-if="current == 1">
          <p-form
            layout="inline"
            :form="form2"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
            @submit="handleSubmit2"
            style="margin-bottom: 1em"
          >
            <p-form-item label="查询条件">
              <p-input
                placeholder="名称 "
                v-decorator="['companyName', { rules: [{ required: false, message: '该项不能为空！' }] }]"
              />
            </p-form-item>
            <p-form-item :wrapper-col="{ span: 5, offset: 5 }">
              <p-button type="" icon="search" html-type="submit"> 查询 </p-button>
            </p-form-item>
          </p-form>
          <p-table
            row-key="id"
            :columns="columns2"
            :hasRowCount="false"
            @change="changePagination"
            :data-source="dataSource2"
          >
          </p-table>
        </div>
        <!-- 第三步 -->
        <div v-else-if="current == 2">
          <p-form
            layout="inline"
            :form="form3"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
            @submit="handleSubmit3"
            style="margin-bottom: 1em"
          >
            <p-form-item label="查询条件">
              <p-input
                placeholder="名称 "
                v-decorator="['companyName', { rules: [{ required: false, message: '该项不能为空！' }] }]"
              />
            </p-form-item>
            <p-form-item :wrapper-col="{ span: 5, offset: 5 }">
              <p-button type="" icon="search" html-type="submit"> 查询 </p-button>
            </p-form-item>
          </p-form>
          <p-table
            row-key="id"
            :columns="columns3"
            :hasRowCount="false"
            @change="changePagination"
            :data-source="dataSource3"
          >
          </p-table>
        </div>
        <!-- 第四步 -->
        <div v-else-if="current == 3">
          <p-form
            layout="inline"
            :form="form4"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
            @submit="handleSubmit4"
            style="margin-bottom: 1em"
          >
            <p-form-item label="查询条件">
              <p-input
                placeholder="名称 "
                v-decorator="['companyName', { rules: [{ required: false, message: '该项不能为空！' }] }]"
              />
            </p-form-item>
            <p-form-item :wrapper-col="{ span: 5, offset: 5 }">
              <p-button type="" icon="search" html-type="submit"> 查询 </p-button>
            </p-form-item>
          </p-form>
          <p-table
            row-key="id"
            :columns="columns4"
            :hasRowCount="false"
            @change="changePagination"
            :data-source="dataSource4"
          >
          </p-table>
        </div>
        <!-- 最后第五步 完成 -->
        <div v-else-if="current == 4">
          <a-result status="success" title="完成" sub-title=""> </a-result>
        </div>
        <div style="background-color: rgba(0, 0, 0, 0.05); width: 100%; height: 1px; margin: 2em 0"></div>
        <!-- 按钮 -->
        <div class="steps-action">
          <!-- 只要不是第一步，显示上一步 -->
          <p-button v-if="current > 1" style="margin-left: 8px" @click="prev"> 上一步 </p-button>
          <!-- 最后一步及点击时-->
          <p-button v-if="current == steps.length - 1" type="primary" @click="handleOk"> 完成 </p-button>
          <!-- 只要不是最后一步，显示下一步 -->
          <p-button v-if="current < steps.length - 1" type="primary" @click="nextStep"
            ><span v-if="current < 1">保存 . </span> 下一步
          </p-button>
        </div>
      </div>
    </p-modal>
  </div>
</template>
<script>
import { getAllOrganization, addDataAuthHdr, listCompanyByAuthId, searchPage } from '../api/addAuth.js'
const columns2 = [
  {
    title: '序号',
    align: 'center',
    width: 60,
    customRender: (text, record, index) => `${index + 1}` // 显示每一行的序号
  },
  {
    title: '货主编号',
    dataIndex: 'companyCode',
    key: 'name',
    slots: { title: 'customTitle' },
    scopedSlots: { customRender: 'companyCode' }
  },
  { title: '货主名称', dataIndex: 'companyName', key: 'companyName' },
  { title: '单位类型 ', dataIndex: 'companyType', key: 'companyType' },
  { title: '汇总ID', dataIndex: 'hdrId', key: 'hdrId' },
  { title: '备注', dataIndex: 'remark', key: 'remark' }
]
const columns3 = [
  {
    title: '序号',
    align: 'center',
    width: 60,
    customRender: (text, record, index) => `${index + 1}` // 显示每一行的序号
  },
  {
    title: '仓编号',
    dataIndex: 'companyCode',
    key: 'name',
    slots: { title: 'customTitle' },
    scopedSlots: { customRender: 'companyCode' }
  },
  { title: '仓名称', dataIndex: 'companyName', key: 'companyName' },
  { title: '单位类型 ', dataIndex: 'companyType', key: 'companyType' },
  { title: '汇总ID', dataIndex: 'hdrId', key: 'hdrId' },
  { title: '备注', dataIndex: 'remark', key: 'remark' }
]
const columns4 = [
  {
    title: '序号',
    align: 'center',
    width: 60,
    customRender: (text, record, index) => `${index + 1}` // 显示每一行的序号
  },
  {
    title: '客户编号',
    dataIndex: 'companyCode',
    key: 'name',
    slots: { title: 'customTitle' },
    scopedSlots: { customRender: 'companyCode' }
  },
  { title: '客户名称', dataIndex: 'companyName', key: 'companyName' },
  { title: '单位类型 ', dataIndex: 'companyType', key: 'companyType' },
  { title: '汇总ID', dataIndex: 'hdrId', key: 'hdrId' },
  { title: '备注', dataIndex: 'remark', key: 'remark' }
]
export default {
  props: {
    visibleAdds: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      value: 0,
      authId: '', //'564092020328263680', //新增汇总权限ID
      treeDataTemp: [],
      treeData: [],
      enabled: false,
      columns2,
      columns3,
      columns4,
      form: this.$form.createForm(this),
      form2: this.$form.createForm(this),
      form3: this.$form.createForm(this),
      form4: this.$form.createForm(this),
      current: 0,
      dataSource2: [], // 第二步数据
      dataSource3: [], // 第三步数据
      dataSource4: [], // 第四步数据
      steps: [{ title: '填写信息' }, { title: '货主' }, { title: '机构/仓' }, { title: '贸易伙伴' }, { title: '完成' }],
      options: [
        { value: '0', title: '资源权限' },
        { value: '1', title: '数据权限' }
      ]
    }
  },
  methods: {
    onChange(e) {
      this.enabled = e.target.checked
    },
    handleSubmit(e) {
      e.preventDefault()
      this.authId = ''
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('步骤1: ', values)
          let params = {
            enabled: this.enabled ? 1 : 0,
            name: values.name,
            // orgId:this.value,	//所属组织
            remark: values.remark
          }
          addDataAuthHdr(params).then(res => {
            if (res.success) {
              //新增汇总权限ID
              this.authId = res.data
              console.log('新增汇总权限ID', this.authId)
              this.$message.success(`新增成功！${res.message}`)
              // 新增成功后进入第2步
              this.next({
                num: '564090818114228224',
                pageNum: 1,
                pageSize: 10,
                params: {
                  authId: this.authId, //第一步保存权限汇总ID
                  companyType: 'H', //单位类型 （V 供应商,C 客户,Y 承运商,W 往来单位,S 自有机构,H 货主）
                  companyName: '',
                  type: '0' //[string] 查询类型1关联0未关联
                }
              })
              // 第1步成功则进则入下一步。
              this.current++
            } else {
              this.$message.error(`失败！${res.message}`)
            }
          })
        } else {
          console.log('表单提交报错')
        }
      })
    },
    /* 步骤2 查询 */
    handleSubmit2(e) {
      e.preventDefault()
      this.form2.validateFields((err, values) => {
        if (!err) {
          console.log('第二步查询: ', values)
          this.next({
            num: '564090818114228224',
            pageNum: 1,
            pageSize: 10,
            params: {
              authId: this.authId, //第一步保存权限汇总ID
              companyType: 'H', //单位类型 （V 供应商,C 客户,Y 承运商,W 往来单位,S 自有机构,H 货主）
              companyName: values.companyName,
              type: '0' //[string] 查询类型1关联0未关联
            }
          })
        } else {
          console.log('报错')
        }
      })
    },
    /* 步骤3 查询 */
    handleSubmit3(e) {
      e.preventDefault()
      this.form3.validateFields((err, values) => {
        if (!err) {
          console.log('第三步查询: ', values)
          this.next({
            num: '564090818114228224',
            pageNum: 1,
            pageSize: 10,
            params: {
              authId: this.authId, //第一步保存权限汇总ID
              companyType: 'S', //单位类型 （V 供应商,C 客户,Y 承运商,W 往来单位,S 自有机构,H 货主）
              companyName: values.companyName,
              type: '0' //[string] 查询类型1关联0未关联
            }
          })
        } else {
          console.log('报错')
        }
      })
    },
    /* 步骤4 查询 */
    handleSubmit4(e) {
      e.preventDefault()
      this.form4.validateFields((err, values) => {
        if (!err) {
          console.log('第四步查询: ', values)
          this.next({
            num: '564090818114228224',
            pageNum: 1,
            pageSize: 10,
            params: {
              authId: this.authId, //第一步保存权限汇总ID
              companyType: 'V,C,Y,W', //单位类型 （V 供应商,C 客户,Y 承运商,W 往来单位,S 自有机构,H 货主）
              companyName: values.companyName,
              type: '0' //[string] 查询类型1关联0未关联
            }
          })
        } else {
          console.log('报错')
        }
      })
    },
    // 步骤2 通用的表格列表查询
    next(params) {
      // 根据权限ID查询关联单位列表 post
      searchPage(params).then(res => {
        if (res.success) {
          switch (this.current) {
            // 第2步
            case 1:
              this.dataSource2 = res.data.list
              break
            // 第3步
            case 2:
              this.dataSource3 = res.data.list
              break
            // 第4步
            case 3:
              this.dataSource4 = res.data.list
              break
            default:
              this.current++
          }
        } else {
          this.$message.error(`查询失败！${res.message}`)
        }
      })
    },
    // 点击切换步骤时触发，回调参数(current) => void
    nextStep() {
      console.log('当前步骤:', this.current)
      switch (this.current) {
        case 0:
          this.handleSubmit(event)
          // this.current++;  //下一步  暂打开
          break
        default:
          this.current++
      }
    },
    prev() {
      this.current--
      console.log('当前步骤:', this.current)
    },
    showModal() {
      this.$emit('update:visibleAdds', true)
    },
    // 点击切换步骤时触发，回调参数(current) => void
    nextStep() {
      console.log('当前步骤:', this.current)
      switch (this.current) {
        case 0:
          this.handleSubmit(event)
          // this.current++;  //下一步  暂打开
          break
        default:
          this.current++
      }
    },
    prev() {
      this.current--
      console.log('当前步骤:', this.current)
    },
    showModal() {
      this.$emit('update:visibleAdds', true)
    },
    handleOk(e) {
      this.$message.success('已完成！')
      this.current = 0
      this.$emit('update:visibleAdds', false)
    },
    handleCancel(e) {
      this.$emit('update:visibleAdds', false)
    },
    enlargeChange(isEnlarge) {
      console.log(isEnlarge)
    },
    changePagination(pagination, filters, sorter) {
      // 分页变化
      console.log(pagination, filters, sorter, '分页变化分页变化')
    },

    // 组织结构处理
    resultTreeNodes(data, key = 'id') {
      let map = {}
      data.forEach(item => {
        delete item.children
        item.leaf = true
        item.isLeaf = true
        map[item[key]] = item
      })
      let value = []
      data.forEach(item => {
        var p = map[item.parentId]
        if (p) {
          if (!p.children) {
            p.children = []
          }
          //p.children.push(item);
          p.children.push(Object.assign(item, { title: item.name, value: item.id, key: item.id }))
          p.leaf = false
          p.isLeaf = false
        } else {
          //if (item.parentId == 0) value.push(item);
          if (item.parentId == 0) value.push(Object.assign(item, { title: item.name, value: item.id, key: item.id }))
        }
      })
      return value
    }
    // treeSelect树选择
  }, //methods
  watch: {
    current: function(nVal, oVal) {
      console.log('当前第步骤nVal，旧步骤:', nVal, oVal)
      // 当前第2步 ==1，选执行第一步保存，再到第2步。
      // if(nVal==1) { this.handleSubmit(event);  }
      // 当前第3步
      if (nVal == 2) {
        this.next({
          num: '564090818114228224',
          pageNum: 1,
          pageSize: 10,
          params: {
            authId: this.authId, //第一步保存权限汇总ID
            companyType: 'S', //单位类型 （V 供应商,C 客户,Y 承运商,W 往来单位,S 自有机构,H 货主）
            companyName: '',
            type: '0' //[string] 查询类型1关联0未关联
          }
        })
      }
      // 当前第4步
      if (nVal == 3) {
        this.next({
          num: '564090818114228224',
          pageNum: 1,
          pageSize: 10,
          params: {
            authId: this.authId, //第一步保存权限汇总ID
            companyType: 'V,C,Y,W', //单位类型 （V 供应商,C 客户,Y 承运商,W 往来单位,S 自有机构,H 货主）
            companyName: '',
            type: '0' //[string] 查询类型1关联0未关联
          }
        })
      }
      // 当前第5步
      if (nVal == 4) {
        setTimeout(() => {
          this.current = 0
          this.$emit('update:visibleAdds', false)
        }, 1000)
      }
    }
  },
  created() {
    // 获取全部组织结构
    /* getAllOrganization().then(res=>{
     if (res.success) {
       console.log(res);
       this.treeData = this.resultTreeNodes(res.data);
       console.log(this.treeData, 'this.treeDatathis.treeData');
     }
   }) */
  },
  mounted() {}
}
</script>
<style scoped lang="less">
.steps-content {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 200px;
  text-align: center;
  padding-top: 80px;
}

.steps-action {
  margin-top: 24px;
  text-align: right;
  .ant-btn-primary {
    margin-left: 1em;
  }
}
</style>
