<template>
  <div>
    <p-card title="路径方向方案配置">
      <span slot="extra">
        <p-button type="primary" @click="showmodel()">新增 </p-button>
      </span>

      <p-grid-form :label-col="{ span: 8 }" :span="8" :items="config.items" @submit="hanlderSubmit" />

      <p-table ref="table" row-key="key" bordered :columns="config.columns" :remoteParams="remoteParams"
        :remoteUrl="config.remoteUrl" :rowSelectType="false" :data-source="data" key="key">
        <template slot="operation" slot-scope="text, record">
          <!-- {{ text ? '禁用' : '启用' }} -->
          <a @click="showmodel(text)">修改</a>
          <a-divider type="vertical" />
          <a @click="dtmodify(text)">明细配置</a>
          <a-divider type="vertical" />
          <a @click="del(text)">删除</a>
        </template>
      </p-table>
    </p-card>
    <p-modal title="新增" width="50%" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk"
      @cancel="handleCancel">
      <p-grid-form :label-col="{ span: 8 }" ref="model" :span="8" :items="config.Modelitems" />
    </p-modal>
    <p-modal :title="current.planName" width="85%" :visible="visiblerelation" :confirm-loading="confirmLoading"
      @ok="handleOkEdit" @cancel="handleCancel">

      <div>
        <p-transfer :data-source="mockData" :target-keys="targetKeys" :disabled="disabled" :show-search="showSearch"
          :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1" :show-select-all="false"
          @change="onChange">
          <template slot="children" slot-scope="{
               props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
               on: { itemSelectAll, itemSelect },
             }">
            <p-table :row-selection="
                 getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })
               " :columns="direction === 'left' ? leftColumns : rightColumns" row-key="key"
              :data-source="filteredItems" size="small" :style="{ pointerEvents: listDisabled ? 'none' : null }"
              :custom-row="
                 ({ key, disabled: itemDisabled }) => ({
                   on: {
                     click: () => {                       
                       //if (itemDisabled || listDisabled) return;
                       //itemSelect(key, !selectedKeys.includes(key));
                     },
                   },
                 })
               ">
              <template slot="operation" slot-scope="text, record">
                <!-- {{ text ? '禁用' : '启用' }} -->
                <a @click="disableEvent(text)">禁用</a>
                <a-divider type="vertical" />
                <a @click="enableEvent(text)">启用</a>
              </template>
            </p-table>
          </template>
        </p-transfer>
      </div>
    </p-modal>
  </div>
</template>
<script>
  import config from './config.js'

  import {
    add,
    update,
    del,
    additem,
    enable,
    disable,
    querySelectAllItem
  } from './api'

  const leftTableColumns = [{
      dataIndex: 'sourceAreaNo',
      title: '起点',
    },
    {
      dataIndex: 'targetAreaNo',
      title: '终点',
    },
    {
      dataIndex: 'isEnable',
      title: '状态',
      customRender(text) {
        text == 0 && (text = '启用')
        text == 1 && (text = '禁用')
        return text
      }
    },
  ];
  const rightTableColumns = [{
      dataIndex: 'planId',
      title: '计划明细id',
      visible: false,
      ellipsis: true,
      width: 100,
    }, {
      dataIndex: 'sourceAreaNo',
      title: '起点',
      width: 80,
    },
    {
      dataIndex: 'targetAreaNo',
      title: '终点',
      ellipsis: true,
      width: 80,
    }, {
      dataIndex: 'isEnable',
      title: '状态',
      ellipsis: true,
      align: 'center',
      width: 100,
      customRender(text) {
        text == 0 && (text = '启用')
        text == 1 && (text = '禁用')
        return text
      }
    }, {
      title: '操作',
      key: 'operation',
      scopedSlots: {
        customRender: 'operation'
      },
      align: 'center'
    }

  ];

  export default {
    data() {
      return {
        config,
        data: [],
        remoteParams: {
          id: "",
          planName: "",
          remark: "",
          isIssue: "",
          isCancel: ""
        },
        visible: false,
        visiblerelation: false,
        confirmLoading: false,

        current: {},

        originTargetKeys: [],
        mockData: [],
        targetKeys: [],
        disabled: false,
        showSearch: false,
        leftColumns: leftTableColumns,
        rightColumns: rightTableColumns,
      }
    },
    created() {
      // for (let i = 1; i < 20; i++) {
      //         if (i % 2 === 0) {
      //           this.mockData.push({
      //             key: i.toString(),
      //             sourceAreaNo: `content${i + 1}`,
      //             targetAreaNo: `description of content${i + 1}`,
      //             isEnable: 1,
      //             isSelect: false
      //           });
      //         } else {
      //           this.mockData.push({
      //             key: i.toString(),
      //             sourceAreaNo: `content${i + 1}`,
      //             targetAreaNo: `description of content${i + 1}`,
      //             isEnable: 1,
      //             isSelect: true
      //           });
      //         }
      //       }

      //       this.originTargetKeys = this.mockData.filter(item => item.isSelect === true).map(item => item.key);
      //       this.targetKeys = this.originTargetKeys
    },
    methods: {
      triggerDisable(disabled) {
        this.disabled = disabled;
      },

      triggerShowSearch(showSearch) {
        this.showSearch = showSearch;
      },
      async del(value) {
        let res = await del(value)
        console.log(res)
        if (res.success) {
          this.$message.success(res.message)
          this.remoteParams = {
            ...this.remoteParams
          }
        } else {
          this.$exception(res)
        }
      },
      async initValueData() {
        let pageNum = 1
        let pageSize = 15
        let res = await querySelectAllItem({
          id: this.current.id,
          pageNum: 1,
          pageSize: 15
        })
        console.log(res)
        if (res.success) {
          this.mockData = res.data.list.map((item, index) => {
            return Object.assign(item, {
              key: item.id
            })
          })
          //const originTargetKeys = mockData.filter(item => +item.key % 4 > 1).map(item => item.key);
          console.log(this.mockData)
          this.originTargetKeys = this.mockData.filter(item => item.isCheck == 1).map(item => item.id);
          console.log(this.originTargetKeys)
          this.targetKeys = this.originTargetKeys

        } else {
          this.visible = false
          this.$exception(res)
        }
      },
      hanlderSubmit(e, form) {
        e.preventDefault()
        form.validateFields((error, values) => {
          console.log(error, values, 'valuesvaluesvaluesvaluesvalues')
          if (!error) {
            this.remoteParams = {
              ...this.remoteParams,
              ...values
            }
          }
        })
      },
      handleOk(e) {
        this.$refs.model.form.validateFields(async (err, value) => {
          if (!err) {
            console.log("修改")
            this.confirmLoading = true
            if (this.type) {
              let res = await update(value)
              console.log(res)
              if (res.success) {
                this.visible = false
                this.$message.success(res.message)
                this.remoteParams = {
                  ...this.remoteParams
                }
              } else {
                this.visible = false
                this.$exception(res)
              }
            } else {
              console.log("新增")
              let res = await add(value)
              console.log(res)
              if (res.success) {
                this.visible = false
                this.$message.success(res.message)
                this.remoteParams = {
                  ...this.remoteParams
                }
              } else {
                this.visible = false
                this.$exception(res)
              }
            }
            this.confirmLoading = false
          }
        })
      },
      async handleOkEdit(e) {
        console.log(this.targetKeys)
        var object = {
          id: "",
          ids: []
        }
        object.id = this.current.id
        object.ids = this.targetKeys
        console.log(object)
        let res = await additem(object)
        console.log(res)
        if (res.success) {
          this.$message.success(res.message)
          this.visiblerelation = false

        } else {
          this.visible = false
          this.$exception(res)
        }
      },
      dtmodify(text) {
        this.current = text
        this.initValueData();
        this.visiblerelation = true
      },
      handleCancel(e) {
        this.current = {}
        this.visible = false
        this.visiblerelation = false
      },

      //点击弹出
      showmodel(data) {
        console.log(data)
        this.visible = true
        if (data) {
          this.config.Modelitems.forEach(item => {
            item.name == 'planName' && (item.disabled = false)
            item.name == 'remark' && (item.disabled = false)
            item.name == 'id' && (item.visible = true)

          })

          this.$nextTick(() => {
            this.$refs.model.form.setFieldsValue(data)
            this.$refs.model.form.setFieldsValue(data)
          })
          this.type = true
        } else {
          this.config.Modelitems.forEach(item => {
            item.name == 'planName' && (item.disabled = false)
            item.name == 'remark' && (item.disabled = false)
            item.name == 'id' && (item.visible = false)


          })
          this.$nextTick(() => {
            this.$refs.model.form.resetFields()
          })
          this.type = false
        }
      },
      onChange(nextTargetKeys) {
        this.targetKeys = nextTargetKeys;
      },

      differenceFun(array, array1) {
        let newArray = []
        array.map((item, index) => {
          if (!array1.includes(item)) {
            newArray.push(item)
          }
        })
        return newArray
      },

      getRowSelection({
        disabled,
        selectedKeys,
        itemSelectAll,
        itemSelect
      }) {
        let that = this
        return {
          getCheckboxProps: item => ({
            props: {
              disabled: disabled || item.disabled
            }
          }),
          onSelectAll(selected, selectedRows) {
            const treeSelectedKeys = selectedRows
              .filter(item => !item.disabled)
              .map(({
                key
              }) => key);
            const diffKeys = selected ?
              that.differenceFun(treeSelectedKeys, selectedKeys) :
              that.differenceFun(selectedKeys, treeSelectedKeys);
            itemSelectAll(diffKeys, selected);
          },
          onSelect({
            key
          }, selected) {
            itemSelect(key, selected);
          },
          selectedRowKeys: selectedKeys,
        };
      },

      async disableEvent(text) {
        console.log(text)
        text.isEnable = 1
        let res = await disable({
          id: text.planId,
          isEnable: 1
        })
        console.log(res)
        if (res.success) {
          this.visible = false
          this.$message.success(res.message)
          this.remoteParams = {
            ...this.remoteParams
          }
        } else {
          this.visible = false
          this.$exception(res)
        }
      },

      async enableEvent(text) {
        console.log(text)
        text.isEnable = 0
        let res = await enable({
          id: text.planId,
          isEnable: 0
        })
        console.log(res)
        if (res.success) {
          this.visible = false
          this.$message.success(res.message)
          this.remoteParams = {
            ...this.remoteParams
          }
        } else {
          this.visible = false
          this.$exception(res)
        }
      }

    }
  }
</script>

<style>
  .ant-transfer {
    display: flex;
    align-self: center
  }



  .ant-transfer-customize-list .ant-transfer-operation {
    flex: 1;
    align-self: center;
  }

  .ant-transfer-operation {
    display: inline-block;
    margin: 0 8px;
    overflow:inherit;
    vertical-align: middle;
    width: 100px;
    


  }
</style>
